登录
首页 >  Golang >  Go教程

Golang处理JSON接口的net/http教程

时间:2025-10-05 10:30:30 477浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《Golang处理JSON接口的net/http教程》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

答案是使用net/http包结合json.NewDecoder和json.NewEncoder处理JSON请求与响应。首先定义可导出的结构体并添加json标签,如User和Response;在Handler中通过json.NewDecoder(r.Body).Decode(&user)解析POST或PUT请求的JSON数据,并校验请求方法与格式;处理完成后,设置Header的Content-Type为application/json,使用json.NewEncoder(w).Encode返回结构化响应。完整示例如创建用户接口,启动HTTP服务监听8080端口,实现JSON数据的解析与返回。

Golang使用net/http处理JSON接口数据

在Go语言中,使用net/http包处理JSON接口数据非常常见,尤其是在构建RESTful API时。核心在于正确解析客户端发送的JSON请求体,并以JSON格式返回响应。下面介绍如何实现请求解析和响应返回。

解析JSON请求

当客户端通过POST或PUT请求发送JSON数据时,服务端需要读取请求体并将其反序列化为Go结构体。

使用json.Unmarshal可以将JSON数据映射到结构体。注意要确保结构体字段可导出(大写开头),并添加json标签以便正确匹配字段。

示例:

定义一个用户结构体:

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

在Handler中解析JSON:

func createUser(w http.ResponseWriter, r *http.Request) {
    var user User
    // 判断请求方法
    if r.Method != "POST" {
        http.Error(w, "只支持POST方法", http.StatusMethodNotAllowed)
        return
    }
    // 解析JSON请求体
    err := json.NewDecoder(r.Body).Decode(&user)
    if err != nil {
        http.Error(w, "无法解析JSON", http.StatusBadRequest)
        return
    }
    // 处理数据(例如保存到数据库)
    fmt.Printf("收到用户: %+v\n", user)
    // 返回成功响应
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(map[string]string{"status": "success", "message": "用户创建成功"})
}

返回JSON响应

向客户端返回JSON数据时,需设置响应头Content-Type: application/json,然后使用json.NewEncoder将数据编码并写入响应流。

常见做法是定义统一的响应结构:

type Response struct {
    Status  string      `json:"status"`
    Message string      `json:"message,omitempty"`
    Data    interface{} `json:"data,omitempty"`
}

使用示例:

func getUser(w http.ResponseWriter, r *http.Request) {
    user := User{Name: "张三", Email: "zhangsan@example.com"}
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(Response{
        Status:  "success",
        Message: "获取成功",
        Data:    user,
    })
}

完整服务示例

以下是一个简单的HTTP服务,包含JSON请求处理和响应返回:

package main

import (
    "encoding/json"
    "log"
    "net/http"
)

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

type Response struct {
    Status  string      `json:"status"`
    Message string      `json:"message,omitempty"`
    Data    interface{} `json:"data,omitempty"`
}

func createUser(w http.ResponseWriter, r *http.Request) {
    if r.Method != "POST" {
        http.Error(w, "不支持的方法", http.StatusMethodNotAllowed)
        return
    }

    var user User
    if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
        http.Error(w, "JSON格式错误", http.StatusBadRequest)
        return
    }

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(Response{
        Status:  "success",
        Message: "用户已创建",
        Data:    user,
    })
}

func main() {
    http.HandleFunc("/user", createUser)
    log.Println("服务器启动在 :8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

基本上就这些。只要掌握json.NewDecoder(r.Body).Decodejson.NewEncoder(w).Encode的使用,就能高效处理大多数JSON接口场景。注意错误处理和Content-Type设置,避免前端解析失败。

本篇关于《Golang处理JSON接口的net/http教程》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>