Go Web开发示例
概述
本文档展示了Go语言的Web开发特性,包括HTTP服务器、路由、中间件、模板、数据库连接等。
运行示例
bash
cd apps/go/examples/03-web
go run main.go
核心概念
1. HTTP服务器
Go标准库提供了强大的HTTP服务器支持。
go
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
http.ListenAndServe(":8080", nil)
}
2. 路由处理
go
func handleHome(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "首页")
}
func handleAbout(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "关于我们")
}
func main() {
http.HandleFunc("/", handleHome)
http.HandleFunc("/about", handleAbout)
http.ListenAndServe(":8080", nil)
}
3. 中间件
go
func loggingMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("请求: %s %s\n", r.Method, r.URL.Path)
next(w, r)
fmt.Println("请求处理完成")
}
}
4. JSON处理
go
import "encoding/json"
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
func handleUsers(w http.ResponseWriter, r *http.Request) {
users := []User{
{ID: 1, Name: "张三", Age: 25},
{ID: 2, Name: "李四", Age: 30},
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(users)
}
5. 模板渲染
go
import "html/template"
func handleTemplate(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.New("hello").Parse(`
<html>
<head><title>{{.Title}}</title></head>
<body>
<h1>{{.Title}}</h1>
<p>{{.Message}}</p>
</body>
</html>
`))
data := struct {
Title string
Message string
}{
Title: "Go Web开发",
Message: "欢迎学习Go Web开发!",
}
tmpl.Execute(w, data)
}
示例代码
详细示例请查看 main.go
文件,包含:
- 基本的HTTP服务器
- 路由处理
- 中间件实现
- JSON API
- 模板渲染
- 静态文件服务
- 表单处理
- 会话管理
常用Web框架
- Gin: 高性能的HTTP Web框架
- Echo: 高性能、可扩展的Web框架
- Fiber: Express.js风格的Web框架
- Chi: 轻量级、快速的路由器
- Gorilla Mux: 强大的URL路由器和分发器
学习要点
- 标准库: 使用net/http包构建Web服务
- 路由: 处理不同的URL路径
- 中间件: 实现请求处理管道
- 模板: 动态生成HTML内容
- JSON: 构建RESTful API
- 安全: 防止常见Web攻击
下一步
- 学习微服务架构 (04-microservice)
- 学习性能优化 (05-performance)
- 学习部署运维 (06-deployment)