gin/sync_async/main.go

28 lines
567 B
Go
Raw Normal View History

2024-09-18 00:04:45 +08:00
package main
import (
"github.com/gin-gonic/gin"
"log"
"time"
)
func main() {
r := gin.Default()
r.GET("/log_async", func(c *gin.Context) {
//1.异步
//启动goroutine时不应该使用原始上下文应该使用副本来处理
copyContext := c.Copy()
go func() {
//异步处理
time.Sleep(3 * time.Second)
log.Println("异步执行:" + copyContext.Request.URL.Path)
}()
})
//2.同步
r.GET("/log_sync", func(c *gin.Context) {
time.Sleep(3 * time.Second)
log.Println("同步执行:" + c.Request.URL.Path)
})
r.Run(":8000")
}