登录
首页 >  Golang >  Go教程

Golang快速搭建RESTAPI指南

时间:2025-11-23 09:07:27 438浏览 收藏

从现在开始,努力学习吧!本文《Golang快速搭建REST API教程》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!

答案:使用Golang标准库net/http可快速搭建REST API,定义User结构体和全局切片模拟数据,实现GET请求获取用户列表和单个用户,通过json.NewEncoder设置Content-Type为application/json并返回JSON数据;利用Gorilla Mux增强路由功能,支持路径参数提取和HTTP方法限制,添加POST处理函数createUser解析请求体中的JSON数据,生成新ID并追加到用户列表,返回状态码201及创建的用户信息,完整实现基础RESTful接口。

Golang如何搭建简单的REST API服务

用Golang搭建一个简单的REST API服务并不复杂,Go语言标准库已经提供了足够的工具来快速实现。下面是一个清晰、实用的实现方式,适合初学者上手。

使用标准库 net/http 创建基础服务

Go 的 net/http 包可以轻松启动HTTP服务并处理路由和请求。以下是一个最简REST服务示例:

package main

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

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

var users = []User{
    {ID: 1, Name: "Alice"},
    {ID: 2, Name: "Bob"},
}

func getUsers(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(users)
}

func getUser(w http.ResponseWriter, r *http.Request) {
    id := r.URL.Path[len("/users/"):]

    for _, u := range users {
        if strconv.Itoa(u.ID) == id {
            w.Header().Set("Content-Type", "application/json")
            json.NewEncoder(w).Encode(u)
            return
        }
    }
    http.Error(w, "User not found", http.StatusNotFound)
}

func main() {
    http.HandleFunc("/users", getUsers)
    http.HandleFunc("/users/", getUser)
    log.Println("Server starting on :8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

说明:

  • 定义了一个 User 结构体,并初始化一个全局切片作为“数据存储”
  • /users 返回所有用户列表
  • /users/{id} 根据路径提取ID返回单个用户
  • 设置响应头为 JSON 格式,使用 json.NewEncoder 编码输出

使用 Gorilla Mux 增强路由功能

标准库的路由能力有限,Gorilla Mux 是一个流行的第三方路由器,支持命名参数、方法限制等。

安装:

go get github.com/gorilla/mux

改写路由部分:

import "github.com/gorilla/mux"

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/users", getUsers).Methods("GET")
    r.HandleFunc("/users/{id}", getUser).Methods("GET")

    log.Println("Server starting on :8080")
    log.Fatal(http.ListenAndServe(":8080", r))
}

在 getUser 中获取参数:

vars := mux.Vars(r)
id := vars["id"]

这种方式更清晰、安全,也更容易扩展POST、PUT、DELETE等操作。

添加 POST 请求处理示例

实现创建用户功能:

func createUser(w http.ResponseWriter, r *http.Request) {
    var user User
    json.NewDecoder(r.Body).Decode(&user)
    user.ID = len(users) + 1
    users = append(users, user)

    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(user)
}

注册路由:

r.HandleFunc("/users", createUser).Methods("POST")

这样就可以接收JSON格式的用户数据并添加到列表中。

基本上就这些。用Go写REST API可以从标准库开始,逐步引入Mux等工具提升可维护性。不复杂但容易忽略细节,比如设置Header、正确返回状态码。

好了,本文到此结束,带大家了解了《Golang快速搭建RESTAPI指南》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

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