上下文
Context API
Section titled “Context API”Context 提供对请求和响应数据的访问。
获取 Context
Section titled “获取 Context”Fox 处理器可以选择性地接受 *gin.Context 参数:
r.GET("/path", func(c *gin.Context) (any, error) { // 访问 context return response, nil})name := c.Query("name") // 获取查询参数page := c.DefaultQuery("page", "1") // 带默认值r.GET("/user/:id", func(c *gin.Context) { id := c.Param("id")})token := c.GetHeader("Authorization")userAgent := c.Request.UserAgent()var data map[string]anyc.ShouldBindJSON(&data)客户端 IP
Section titled “客户端 IP”ip := c.ClientIP()JSON 响应
Section titled “JSON 响应”c.JSON(200, gin.H{ "message": "success",})c.String(200, "Hello, World!")HTML 响应
Section titled “HTML 响应”c.HTML(200, "index.html", gin.H{ "title": "主页",})c.Redirect(302, "/new-path")c.Status(204) // No ContentContext 数据
Section titled “Context 数据”c.Set("user_id", 123)userID := c.GetInt("user_id")value, exists := c.Get("key")Must Get
Section titled “Must Get”userID := c.MustGet("user_id").(int)file, _ := c.FormFile("file")c.SaveUploadedFile(file, "./uploads/"+file.Filename)form, _ := c.MultipartForm()files := form.File["files"]
for _, file := range files { c.SaveUploadedFile(file, "./uploads/"+file.Filename)}c.File("./assets/image.png")Cookies
Section titled “Cookies”设置 Cookie
Section titled “设置 Cookie”c.SetCookie( "session_id", // name "abc123", // value 3600, // maxAge (seconds) "/", // path "example.com", // domain false, // secure true, // httpOnly)获取 Cookie
Section titled “获取 Cookie”value, err := c.Cookie("session_id")停止处理并返回:
if !isAuthenticated(c) { c.JSON(401, gin.H{"error": "未授权"}) c.Abort() return}Fox 特定方法
Section titled “Fox 特定方法”获取 Logger
Section titled “获取 Logger”logger := fox.GetLogger(c)logger.Info("处理请求")获取 TraceID
Section titled “获取 TraceID”traceID := fox.GetTraceID(c)