Easy-Go-Web3
知识图谱Go 教程React Web3智能合约
需求分析系统设计设计模式Go 微服务
项目实战DevOps
Go 生态React 生态智能合约生态Web3 生态AI × Web3工具箱Web3 公司远程Web3求职
🎯 AA 工程师面试手册博客
GitHub
返回教程列表

Web 开发

使用 Go 构建高性能 Web 服务

3 课时
1

HTTP 基础

Go 标准库 net/http 提供了强大的 HTTP 服务能力,无需第三方框架即可构建生产级别的 Web 服务。

简单 HTTP 服务器

go
1package main
2
3import (
4 "fmt"
5 "net/http"
6)
7
8func helloHandler(w http.ResponseWriter, r *http.Request) {
9 fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
10}
11
12func main() {
13 http.HandleFunc("/", helloHandler)
14
15 fmt.Println("Server starting on :8080")
16 http.ListenAndServe(":8080", nil)
17}
2

路由设计

Go 1.22+ 增强了标准库路由功能,支持路径参数和 HTTP 方法匹配。

RESTful 路由

go
1package main
2
3import (
4 "encoding/json"
5 "net/http"
6)
7
8type User struct {
9 ID string `json:"id"`
10 Name string `json:"name"`
11}
12
13func main() {
14 mux := http.NewServeMux()
15
16 // GET /users/{id}
17 mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
18 id := r.PathValue("id")
19 user := User{ID: id, Name: "Alice"}
20
21 w.Header().Set("Content-Type", "application/json")
22 json.NewEncoder(w).Encode(user)
23 })
24
25 // POST /users
26 mux.HandleFunc("POST /users", func(w http.ResponseWriter, r *http.Request) {
27 var user User
28 json.NewDecoder(r.Body).Decode(&user)
29
30 w.WriteHeader(http.StatusCreated)
31 json.NewEncoder(w).Encode(user)
32 })
33
34 http.ListenAndServe(":8080", mux)
35}
3

中间件

中间件是处理 HTTP 请求的函数,可以在请求到达处理器之前或之后执行逻辑。

自定义中间件

go
1package main
2
3import (
4 "log"
5 "net/http"
6 "time"
7)
8
9// 日志中间件
10func loggingMiddleware(next http.Handler) http.Handler {
11 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
12 start := time.Now()
13
14 next.ServeHTTP(w, r)
15
16 log.Printf("%s %s %v", r.Method, r.URL.Path, time.Since(start))
17 })
18}
19
20// 认证中间件
21func authMiddleware(next http.Handler) http.Handler {
22 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
23 token := r.Header.Get("Authorization")
24 if token == "" {
25 http.Error(w, "Unauthorized", http.StatusUnauthorized)
26 return
27 }
28 next.ServeHTTP(w, r)
29 })
30}
31
32func main() {
33 mux := http.NewServeMux()
34 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
35 w.Write([]byte("Hello"))
36 })
37
38 // 链式中间件
39 handler := loggingMiddleware(authMiddleware(mux))
40 http.ListenAndServe(":8080", handler)
41}
上一章:并发编程下一章:数据库操作
Easy-Go-Web3

构建 Go 后端与 Web3 的学习之路。从基础到进阶,从理论到实践,助你成为全栈区块链开发者。

学习路径

  • 知识图谱
  • Go 教程
  • Go 微服务
  • 面试手册

资源中心

  • 工具箱
  • DevOps 工具
  • Web3 生态
  • 博客

© 2025 Easy-Go-Web3. All rights reserved.

Created withbyhardybao