Golang如何处理HTTP POST和GET请求_Golang HTTP方法处理技巧

Go语言通过net/http处理HTTP请求,GET参数用URL.Query().Get()获取并设默认值,POST请求需解析表单或解码JSON,注意验证方法、Content-Type及关闭Body,统一路由可用switch分支处理不同方法,适合RESTful设计。

Go语言处理HTTP请求非常直观,标准库net/http提供了强大且简洁的接口来处理GET和POST请求。无论是构建API还是Web服务,掌握如何正确解析不同类型的请求是关键。

处理HTTP GET请求

GET请求通常用于获取数据,参数通过URL查询字符串传递。在Go中,可以通过http.Request对象的URL.Query()方法提取参数。

示例:

func handleGet(w http.ResponseWriter, r *http.Request) {
    // 确保是GET请求
    if r.Method != "GET" {
        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        return
    }

    // 获取查询参数
    name := r.URL.Query().Get("name")
    age := r.URL.Query().Get("age")

    if name == "" {
        name = "Guest"
    }

    fmt.Fprintf(w, "Hello %s, you are %s years old", name, age)
}

// 注册路由
http.HandleFunc("/get", handleGet)

说明:使用r.URL.Query().Get()安全获取参数,若参数不存在会返回空字符串,需做默认值处理。

处理HTTP POST请求

POST请求常用于提交数据,数据体可能为表单、JSON等格式。Go能自动解析表单数据,对JSON则需要手动解码。

处理表单数据:

func handlePostForm(w http.ResponseWriter, r *http.Request) {
    if r.Method != "POST" {
        http.Error(w, "Invalid method", http.StatusMethodNotAllowed)
        return
    }

    // 解析表单(支持application/x-www-form-urlencoded)
    err := r.ParseForm()
    if err != nil {
        http.Error(w, "Bad request", http.StatusBadRequest)
        return
    }

    username := r.FormValue("username")
    email := r.FormValue("email")

    fmt.Fprintf(w, "Received: %s (%s)", username, email)
}

处理JSON数据:

type User struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}

func handlePostJSON(w http.ResponseWriter, r *http.Request) {
    if r.Method != "POST" {
        http.Error(w, "Invalid method", http.StatusMethodNotAllowed)
        return
    }

    // 判断Content-Type是否为application/json
    if r.Header.Get("Content-Type") != "application/json" {
        http.Error(w, "Content-Type must be application/json", http.StatusUnsupportedMediaType)
        return
    }

    var user User
    decoder := json.NewDecoder(r.Body)
    if err := decoder.Decode(&user); err != nil {
        http.Error(w, "Invalid JSON", http.StatusBadRequest)
        return
    }
    defer r.Body.Close()

    fmt.Fprintf(w, "User: %+v", user)
}

统一处理多种请求方法

一个路由可能需要支持多种HTTP方法,可通过判断r.Method来分支处理。

func handler(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case "GET":
        handleGet(w, r)
    case "POST":
        handlePostForm(w, r)
    default:
        http.Error(w, "Unsupported method", http.StatusMethodNotAllowed)
    }
}

这种方式适合RESTful接口设计,例如同一个路径下GET获取资源,POST创建资源。

实用技巧与注意事项

  • 始终验证请求方法,避免误处理
  • 处理JSON时检查Content-Type,防止客户端发送错误格式
  • 调用ParseForm()后才能使用FormValue()
  • 读取完request body后记得关闭(defer r.Body.Close())
  • 返回响应前设置合适的Header,如w.Header().Set("Content-Type", "application/json")
基本上就这些。Go的标准库足够应对大多数场景,不需要额外框架也能写出清晰可靠的HTTP服务。