Skip to content
返回

2026-01-12 Go结合Gin框架开发Web

![[../../../assets/images/pub/rzyd.webp]]

目录

点击展开

体验内置库

可以先体验下go内置的http web库,net/http

main.go

package main

import (
	"fmt"
	"net/http"
)

func SayHello(w http.ResponseWriter, r *http.Request) {
	// 写入响应
	fmt.Fprintf(w, "hello world")
}

func main() {
	// 路由,匹配后执行
	http.HandleFunc("/hello", SayHello)
	// 启动服务
	err := http.ListenAndServe(":9000", nil)

	if err != nil {
		fmt.Printf("http server start failed, err: %v", err)
		return
	}

}

直接执行go run main.go 执行成功后,在浏览器地址栏中访问http://localhost:9000/hello即可 ![[../../../assets/images/2026/Pasted image 20260130162329.png]]

什么是Gin?

Gin 是一个基于 Go 语言(Golang)的 服务端高性能 HTTP Web 框架,广泛用于构建 API 服务、Web 应用、微服务等场景。

Gin 的核心特性:

官网:https://gin-gonic.com/

快速体验Gin

安装

go get -u github.com/gin-gonic/gin

引入使用

main.go

package main

import "github.com/gin-gonic/gin"

func sayHello(c *gin.Context) {
	// gin.H 是 map[string]interface{} 的一种快捷方式
	c.JSON(200, gin.H{
		"message": "hello world",
	})
}

func main() {
	gin.SetMode("release")  // 设置gin的运行模式为release,默认为debug模式
	router := gin.Default() // 创建默认路由引擎
	// 指定用户使用GET请求访问/hello时,执行sayHello这个函数
	router.GET("/hello", sayHello)

	// 启动服务
	err := router.Run(":9000")
	if err != nil {
		return
	}

}

直接执行go run main.go 执行成功后,在浏览器地址栏中访问http://localhost:9000/hello即可 ![[../../../assets/images/2026/Pasted image 20260130165836.png]]

响应封装

新建 res.go文件

package gin

import (
	"github.com/gin-gonic/gin"
)

type Response struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data any    `json:"data"`
}

func response(c *gin.Context, code int, msg string, data any) {
	c.JSON(200, Response{
		Code: code,
		Msg:  msg,
		Data: data,
	})
}

func Ok(c *gin.Context, data any, msg string) {
	response(c, 0, msg, data)
}

func OkWithData(c *gin.Context, data any) {
	Ok(c, data, "success")

}

func OkWithMsg(c *gin.Context, msg string) {
	// nil前端调用返回值是 null, 使用gin.H{}, 前端调用返回值是 {}
	Ok(c, gin.H{}, msg)
}

var codeMap = map[int]string{
	1001: "权限错误",
	1002: "参数错误",
}

func Fail(c *gin.Context, code int, data any, msg string) {
	response(c, code, msg, data)
}

func FailWithMsg(c *gin.Context, msg string) {
	response(c, 1001, msg, nil)
}

func FailWithCode(c *gin.Context, code int) {
	msg, ok := codeMap[code]
	if !ok {
		msg = "未知错误"
	}
	response(c, code, msg, nil)
}

同包下可以直接在main.go中使用 main.go

package main

import "github.com/gin-gonic/gin"

func sayHello(c *gin.Context) {
	// gin.H 是 map[string]interface{} 的一种快捷方式
	c.JSON(200, gin.H{
		"message": "hello world",
	})
}

func main() {
	router := gin.Default() 
	router.GET("/hello", sayHello)
	
	router.GET("/login", func(c *gin.Context) {
		OkWithMsg(c, "登录成功")
	})

	router.GET("/user", func(c *gin.Context) {
		OkWithData(c, map[string]any{
			"name": "张三",
			"age":  23,
		})
	})

	router.POST("/user", func(c *gin.Context) {
		FailWithMsg(c, "参数错误")
	})


	// 启动服务
	err := router.Run(":9000")
	if err != nil {
		return
	}

}

可以使用热门的API管理工具:PostmanApifoxApipost 调试

生态与扩展

Gin 本身是「核心框架」,但生态丰富,可搭配以下工具满足复杂需求:

数据库:GORM(Go 语言 ORM 框架)、xorm; 认证授权:gin-jwt(JWT 认证)、gin-authz(基于 Casbin 的权限控制); 限流熔断:gin-rate-limit(限流)、hystrix-go(熔断); 日志监控:zap(高性能日志)、prometheus + grafana(监控); 模板渲染:Gin 内置 HTML 模板引擎(c.HTML()),支持模板继承、变量渲染; API 文档:swaggo/gin-swagger(自动生成 Swagger 文档)。

![[../../../assets/images/pub/clw.webp#pic_center)]]




Share this post on:

上一篇文章
2025-12-26 Redux 快速学习上手、简单易懂
下一篇文章
Go语言基础