Gin框架学习(四)

本文深入介绍了Gin框架的高级特性,包括同步与异步处理请求,利用goroutine和复制上下文实现异步操作。此外,展示了如何运行多个服务,以及使用路由组进行组织。还探讨了RESTful API设计,包括标准方法和更简便的`Any()`方法。最后,讨论了如何通过`Handle`函数快速注册多种HTTP方法。
摘要由CSDN通过智能技术生成

学习思维导图

Gin框架思维导图

提高篇

同步异步

// 同步
func longSync(context *gin.Context) {
	time.Sleep(3 * time.Second)
	log.Println(context.Request.URL.Path)
}

goroutine机制可以方便地实现异步处理,必须使用它的只读副本!

// 异步
func longAsync(context *gin.Context) {
	copyContext := context.Copy()
	go func() {
		time.Sleep(3 * time.Second)
		log.Println(copyContext.Request.URL.Path)
	}()
}

多服务程序运行

package main

import (
	"log"
	"net/http"
	"time"
	"github.com/gin-gonic/gin"
	"golang.org/x/sync/errgroup"
)
var (g errgroup.Group)
func router01() http.Handler {
	e := gin.New()
	e.Use(gin.Recovery())
	e.GET("/", func(c *gin.Context) {
		c.JSON(
			http.StatusOK,
			gin.H{
				"code":  http.StatusOK,
				"error": "Welcome server 01",
			},
		)
	})
	return e
}
func router02() http.Handler {
	e := gin.New()
	e.Use(gin.Recovery())
	e.GET("/", func(c *gin.Context) {
		c.JSON(
			http.StatusOK,
			gin.H{
				"code":  http.StatusOK,
				"error": "Welcome server 02",
			},
		)
	})
	return e
}
func main() {
	server01 := &http.Server{
		Addr:         ":8080",
		Handler:      router01(),
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 10 * time.Second,
	}
	server02 := &http.Server{
		Addr:         ":8081",
		Handler:      router02(),
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 10 * time.Second,
	}
	g.Go(func() error {
		return server01.ListenAndServe()
	})
	g.Go(func() error {
		return server02.ListenAndServe()
	})
	if err := g.Wait(); err != nil {
		log.Fatal(err)
	}
}

路由组

路由
package main

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

func main() {
	r := gin.Default()
	//获取信息
	r.GET("/index", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"method": "GET",
		})
	})
	//创建信息
	r.POST("/index", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"method": "POST",
		})
	})
	//更新信息
	r.PUT("/index", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"method": "PUT",
		})
	})
	//删除信息
	r.DELETE("/index", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"method": "DELETE",
		})
	})
	//处理所有的请求方法
	r.Any("/user", func(c *gin.Context) {
		switch c.Request.Method{
		case "GET" :
			c.JSON(http.StatusOK, gin.H{
				"method": "GET"
			})
		case http.MethodPost:
			c.JSON(http.StatusOK, gin.H{
				"method":"POST"
			})
		}
		c.JSON(http.StatusOK, gin.H{
			"method": "Any",
		})
	})
路由组
	//路由组
	videoGroup := r.Group("/ajax"){
		videoGroup.GET("/video1", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{
				"msg":"/ajax/index1"
			})
		})
		videoGroup.GET("/index2", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{
				"msg":"/ajax/index2"
			})
		})
		videoGroup.GET("/index3", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{
				"msg":"/ajax/index3"
			})
		})
	}
	r.Run()
}

调用resful 接口(API)

一般方法(建议)
//首先我们定义一个用户User,用来表示我们需要操作的用户
type User struct {
	ID   uint64
	Name string
}
func main() {
	users := []User{{ID: 123, Name: "张三"}, {ID: 456, Name: "李四"}}
	r := gin.Default()
	r.GET("/users", func(c *gin.Context) {
		c.JSON(200, users)
	})
	r.POST("/users", func(context *gin.Context) {
		//创建一个用户
	})
	r.DELETE("/usrs/123", func(context *gin.Context) {
		//删除ID为123的用户
	})
	r.PUT("/usrs/123", func(context *gin.Context) {
		//更新ID为123的用户
	})

	r.PATCH("/usrs/123", func(context *gin.Context) {
		//更新ID为123用户的部分信息
	})
	r.Run(":8080")
}
更简便的方法:Any()
func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes {
	group.handle("GET", relativePath, handlers)
	group.handle("POST", relativePath, handlers)
	group.handle("PUT", relativePath, handlers)
	group.handle("PATCH", relativePath, handlers)
	group.handle("HEAD", relativePath, handlers)
	group.handle("OPTIONS", relativePath, handlers)
	group.handle("DELETE", relativePath, handlers)
	group.handle("CONNECT", relativePath, handlers)
	group.handle("TRACE", relativePath, handlers)
	return group.returnObj()
}
func Handle(r *gin.Engine, httpMethods []string, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes {
	var routes gin.IRoutes
	for _, httpMethod := range httpMethods {
		routes = r.Handle(httpMethod, relativePath, handlers...)
	}
	return routes
}
//有了这个函数,我们就可以类似如下这样使用:
//Handle(r, []string{"GET", "POST"}, "/", func(c *gin.Context) {
		//同时注册GET、POST请求方法
//	})
//虽然这种方式比较便利,但是并不太推荐,因为他破坏了Resultful 规范中HTTP Method的约束。

后记

喜欢的话可以三连,后续继续更新其他内容,帮忙推一推,感谢观看!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北岛末巷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值