在使用 Go语言 开发 Web 应用或 API 时,net/http 包是最核心的网络库之一。其中,Content-Type 是 HTTP 协议中一个非常关键的头部字段,它告诉服务器或客户端请求/响应体的数据格式。本文将从零开始,手把手教你如何在 Go语言 中正确设置和读取 Content-Type,帮助你构建更规范、可靠的 HTTP 通信。
Content-Type 是 HTTP 头部(Header)的一部分,用于指示资源的 MIME 类型(媒体类型)。常见的类型包括:
application/json:JSON 格式数据application/x-www-form-urlencoded:表单提交数据multipart/form-data:上传文件时使用text/plain:纯文本text/html:HTML 页面当你使用 net/http 发起 HTTP 请求(如 POST、PUT)时,需要明确指定请求体的 Content-Type,否则服务器可能无法正确解析你的数据。
下面是一个发送 JSON 数据的完整示例:
package mainimport ( "bytes" "encoding/json" "fmt" "net/http")type User struct { Name string `json:"name"` Email string `json:"email"`}func main() { user := User{Name: "张三", Email: "zhangsan@example.com"} jsonData, _ := json.Marshal(user) // 创建请求 req, err := http.NewRequest("POST", "https://api.example.com/users", bytes.NewBuffer(jsonData)) if err != nil { panic(err) } // 设置 Content-Type 为 application/json req.Header.Set("Content-Type", "application/json") // 发送请求 client := &http.Client{} resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() fmt.Println("请求已发送,状态码:", resp.StatusCode)} 注意:req.Header.Set("Content-Type", "application/json") 这一行是关键!如果没有它,服务器可能会把你的 JSON 当作普通文本处理,导致解析失败。
formData := "name=李四&age=25"req, _ := http.NewRequest("POST", "https://example.com/form", strings.NewReader(formData))req.Header.Set("Content-Type", "application/x-www-form-urlencoded") 文件上传通常使用 multipart.Writer,Go 会自动设置正确的 Content-Type(包含 boundary):
body := &bytes.Buffer{}writer := multipart.NewWriter(body)// 添加普通字段_ = writer.WriteField("title", "我的照片")// 添加文件part, _ := writer.CreateFormFile("file", "photo.jpg")file, _ := os.Open("photo.jpg")defer file.Close()io.Copy(part, file)writer.Close()req, _ := http.NewRequest("POST", "https://example.com/upload", body)req.Header.Set("Content-Type", writer.FormDataContentType()) // 自动设置带 boundary 的 Content-Type 如果你在写 Go 的 HTTP 服务端,也可以通过 r.Header.Get("Content-Type") 获取客户端发送的 Content-Type:
http.HandleFunc("/api/data", func(w http.ResponseWriter, r *http.Request) { contentType := r.Header.Get("Content-Type") fmt.Printf("接收到的 Content-Type: %s\n", contentType) if strings.Contains(contentType, "application/json") { // 按 JSON 解析 var data map[string]interface{} json.NewDecoder(r.Body).Decode(&data) fmt.Fprintf(w, "收到 JSON 数据: %+v", data) } else { http.Error(w, "只支持 JSON 格式", http.StatusBadRequest) }}) 正确使用 Content-Type 是构建健壮 HTTP 通信的基础。在 Go语言 的 net/http 包中,无论是作为客户端还是服务端,都需要关注这个头部字段。记住:
Content-TypeContent-Type 再决定如何解析Content-Type 值,不要混淆掌握这些技巧后,你就能更自信地使用 Go语言 和 net/http 包开发高质量的 Web 应用了!
关键词:Go语言, net/http, Content-Type, HTTP请求
本文由主机测评网于2025-12-21发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://vpshk.cn/20251210727.html