Go 语言 Web 开发入门:从 net/http 到 Gin

2026-09-15 后端开发 有希 178 views

demo data

Go 标准库自带的 net/http 就能写出可用的 Web 服务,本文从标准库出发,过渡到 Gin 框架。

标准库起步

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "pong")
    })
    http.ListenAndServe(":8080", nil)
}

迁移到 Gin

Gin 在标准库之上提供了路由分组、中间件与参数绑定:

r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
    c.JSON(200, gin.H{"message": "pong"})
})
r.Run(":8080")

提示:中间件里记得用 c.Next() 继续调用链。

小结

  • 标准库零依赖,适合小工具
  • 框架省心,适合业务系统

Comments

Sign in to join the discussion

No comments yet — be the first to say something

Related Articles

aiitoo.com © 2026. All Rights Reserved.