go-gin框架测试代码
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
type UserInfo struct {
Name string `json:"name"`
Age int `json:"age"`
Gender string `json:"gender"`
}
func main() {
// 创建一个默认的路由引擎
r := gin.Default()
// GET:请求方式;/hello:请求的路径
// 当客户端以GET方法请求/hello路径时,会执行后面的匿名函数
r.GET("/user", func(c *gin.Context) {
// c.JSON:返回JSON格式的数据
userInfo := UserInfo{
Name: "张建平",
Age: 25,
Gender: "male",
}
c.JSON(http.StatusOK, userInfo)
})
r.GET("book", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "get",
})
})
r.POST("book", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "post",
})
})
r.PUT("book", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "put",
})
})
r.DELETE("book", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "delete",
})
})
// 启动HTTP服务,默认在0.0.0.0:8080启动服务
_ = r.Run(":8080")
}
package main
import (
"encoding/json"
"github.com/gin-gonic/gin"
"html/template"
"log"
"net/http"
"time"
)
type UserInfo struct {
Name string `json:"name"`
Age int `json:"age"`
Gender string `json:"gender"`
}
func StatCost() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
// 中间件写值
c.Set("start", start.String())
c.Next()
cost := time.Since(start)
log.Println(cost)
}
}
func router01() http.Handler {
router := gin.New()
router.Use(gin.Recovery())
router.GET("/router01", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "welcome server 01",
})
})
return router
}
func router02() http.Handler {
router := gin.New()
router.Use(gin.Recovery())
router.GET("/router02", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "welcome server 02",
})
})
return router
}
func main() {
// 创建一个默认的路由引擎
router := gin.Default()
router.Use(StatCost())
router.SetFuncMap(template.FuncMap{
"safe": func(str string) template.HTML {
return template.HTML(str)
},
})
router.LoadHTMLFiles("./index.tmpl")
router.NoRoute(func(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{
"message": "页面未找到",
})
})
_ = map[string]interface{}{
"name": "张建平",
"age": 18,
}
// GET:请求方式;/hello:请求的路径
// 当客户端以GET方法请求/hello路径时,会执行后面的匿名函数
router.GET("/user_1", func(c *gin.Context) {
// c.JSON:返回JSON格式的数据
userInfo := UserInfo{
Name: "张建平",
Age: 25,
Gender: "male",
}
c.JSON(http.StatusOK, userInfo)
})
router.GET("/book", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "get",
})
})
router.POST("/book", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "post",
})
})
router.PUT("/book", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "put",
})
})
router.DELETE("/book", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "delete",
})
})
router.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", "<a href='https://www.baidu.com/'>点击跳转</a>")
})
router.GET("/query", func(c *gin.Context) {
b, _ := c.GetRawData()
var m map[string]interface{}
_ = json.Unmarshal(b, &m)
username := c.DefaultQuery("username", "张建平")
address := c.Query("address")
c.JSON(http.StatusOK, gin.H{
"message": "ok",
"username": username,
"address": address,
"json": m,
})
})
router.GET("/user/search/:username/:address", func(c *gin.Context) {
username := c.Param("username")
address := c.Param("address")
c.JSON(http.StatusOK, gin.H{
"message": "ok",
"username": username,
"address": address,
})
})
router.GET("/redirect_1", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "https://52-qq.cnblogs.com/")
})
router.GET("/redirect_2", func(c *gin.Context) {
c.Request.URL.Path = "/redirect_1"
router.HandleContext(c)
})
router.Any("/any", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "any_ok",
})
})
router.GET("/middle", StatCost(), func(c *gin.Context) {
// 中间件取值
start := c.MustGet("start").(string)
log.Println(start)
c.JSON(http.StatusOK, gin.H{
"message": "middle",
})
})
// 路由组
userGroup := router.Group("/user")
// userGroup.Use(StatCost()) 中间件注册
{
userGroup.GET("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "用户主页",
})
})
userGroup.GET("/home", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "用户家目录",
})
})
userAdminGroup := userGroup.Group("/admin", StatCost()) // 中间件注册
{
userAdminGroup.GET("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "用户管理首页",
})
})
}
}
// 定义中间件
// 启动HTTP服务,默认在0.0.0.0:8080启动服务
_ = router.Run(":8080")
// ##################### 启动多服务 ######################
//server01 := &http.Server{
// Addr: ":8081",
// Handler: router01(),
// ReadTimeout: 5 * time.Second,
// WriteTimeout: 10 * time.Second,
//}
//server02 := &http.Server{
// Addr: ":8082",
// Handler: router02(),
// ReadTimeout: 5 * time.Second,
// WriteTimeout: 10 * time.Second,
//}
// 借助errgroup.Group或者自行开启两个goroutine分别启动两个服务
//g.Go(func() error {
// return server01.ListenAndServe()
//})
//
//g.Go(func() error {
// return server02.ListenAndServe()
//})
//
//if err := g.Wait(); err != nil {
// log.Fatal(err)
//}
}
本文来自博客园,作者:一石数字欠我15w!!!,转载请注明原文链接:https://www.cnblogs.com/52-qq/p/14653645.html
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)