Web 开发实战

Go 教程 · 第 8 章 · 8 次浏览

Go 标准库 net/http 就能写 Web 服务,配合 gin(最流行的框架)开发效率更高。本节用标准库写一个 REST API,再对比 gin。

标准库 Web

http.HandleFunc 注册路由,监听端口。JSON 编解码用 encoding/json。

Gin 框架

go get github.com/gin-gonic/gin。gin.Default() 创建引擎,c.JSON 返回 JSON,路由分组方便。

代码示例

package main

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

type Todo struct {
    ID   int    `json:"id"`
    Text string `json:"text"`
}

var todos = []Todo{{1, "学习 Go"}, {2, "写 API"}}

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

func main() {
    http.HandleFunc("/todos", listHandler)
    http.ListenAndServe(":8080", nil)
}

// 用 gin 的版本(更简洁)
// r := gin.Default()
// r.GET("/todos", func(c *gin.Context) {
//     c.JSON(200, todos)
// })
// r.Run(":8080")