登录
首页 >  Golang >  Go教程

Golang搭建JSON接口服务器教程

时间:2026-02-28 10:43:31 340浏览 收藏

本文手把手教你仅用Golang标准库(net/http和encoding/json)从零搭建一个轻量、高效、并发安全的JSON接口服务器,实现用户管理的完整CRUD功能——包括创建、查询全部/单个用户、更新与删除,并通过map模拟内存存储、sync.Mutex保障多协程安全、简洁路由设计及curl实操验证,让你深入理解RESTful API底层原理,无需依赖任何第三方框架即可快速构建生产级基础服务。

如何使用 Golang 编写一个 JSON 接口服务器_Golang RESTful API 实战演练

构建一个 JSON 接口服务器是 Golang 的常见应用场景。它轻量、高效,非常适合编写 RESTful API。下面通过一个简单的实战示例,带你一步步实现一个支持增删改查(CRUD)的用户管理接口。

初始化项目结构

创建项目目录并初始化模块:

mkdir go-rest-api
cd go-rest-api
go mod init go-rest-api

我们不依赖第三方框架,仅使用标准库 net/http 和 encoding/json,保持简洁。

定义数据模型和存储

创建一个 User 结构体,并使用 map 模拟内存存储:

type User struct {
  ID    int    json:"id"
  Name  string json:"name"
  Email string json:"email"
}

用 map 存储用户数据,配合互斥锁保证并发安全:

var (
  users = make(map[int]User)
  mu   = sync.Mutex{}
  nextID = 1
)

编写处理函数

每个 HTTP 请求对应一个处理函数。这些函数需满足 http.HandlerFunc 签名。

获取所有用户

func getUsers(w http.ResponseWriter, r *http.Request) {
  mu.Lock()
  defer mu.Unlock()
  
  var result []User
  for _, u := range users {
    result = append(result, u)
  }
  
  w.Header().Set("Content-Type", "application/json")
  json.NewEncoder(w).Encode(result)
}

创建用户

func createUser(w http.ResponseWriter, r *http.Request) {
  if r.Method != http.MethodPost {
    http.Error(w, "只允许 POST 方法", http.StatusMethodNotAllowed)
    return
  }
  
  var user User
  if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
    http.Error(w, err.Error(), http.StatusBadRequest)
    return
  }
  
  mu.Lock()
  defer mu.Unlock()
  
  user.ID = nextID
  nextID++
  users[user.ID] = user
  
  w.Header().Set("Content-Type", "application/json")
  w.WriteHeader(http.StatusCreated)
  json.NewEncoder(w).Encode(user)
}

获取单个用户

func getUser(w http.ResponseWriter, r *http.Request) {
  id, _ := strconv.Atoi(r.URL.Path[len("/users/"):])
  mu.Lock()
  defer mu.Unlock()
  
  user, exists := users[id]
  if !exists {
    http.Error(w, "用户不存在", http.StatusNotFound)
    return
  }
  
  w.Header().Set("Content-Type", "application/json")
  json.NewEncoder(w).Encode(user)
}

更新和删除用户 可以类似实现,分别使用 PUT 和 DELETE 方法,解析路径中的 ID 并操作 map。

注册路由并启动服务器

在 main 函数中设置路由并监听端口:

func main() {
  http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
    if r.Method == http.MethodGet {
      getUsers(w, r)
    } else if r.Method == http.MethodPost {
      createUser(w, r)
    }
  })
  
  http.HandleFunc("/users/", func(w http.ResponseWriter, r *http.Request) {
    if r.Method == http.MethodGet {
      getUser(w, r)
    }
  })
  
  fmt.Println("服务器启动在 :8080")
  log.Fatal(http.ListenAndServe(":8080", nil))
}

运行服务后,可用 curl 测试:

curl -X POST http://localhost:8080/users \
  -H "Content-Type: application/json" \
  -d '{"name": "Alice", "email": "alice@example.com"}'

基本上就这些。这个例子展示了如何用 Go 标准库快速搭建一个可用的 JSON 接口服务。虽然没有使用 Gin 或 Echo 等框架,但理解底层机制有助于写出更可控的代码。

好了,本文到此结束,带大家了解了《Golang搭建JSON接口服务器教程》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>