gin-gonic / gin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.

Home Page:https://gin-gonic.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

GetUint and GetUint64 wrong return

bayaderpack opened this issue · comments

Description

I'm trying to use GetUint64 and GetUint but it returns 0

How to reproduce

package main

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

func main() {
	g := gin.Default()
	g.GET("/hello", func(c *gin.Context) {
		c.String(200, "Your ID is %d %d", c.GetUint64("user"), c.GetUint("user"))
	})
	g.Run(":9000")
}

Expectations

$ curl http://localhost:9000/hello?user=1
Your ID is 1 1

Actual result

$ curl -i http://localhost:9000/hello?user=1
Your ID is 0 0

Environment

  • go version: 1.21
  • gin version (or commit ref): 1.9.1
  • operating system: Windows

There is a problem with your usage, you should use BindQuery or ShouldBindQuery.

package main

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

func main() {
	g := gin.Default()
	g.GET("/hello", func(c *gin.Context) {
		m := make(map[string]string)
		if err := c.BindQuery(&m); err != nil {
			c.String(http.StatusInternalServerError,"input data have error: %v",err)
			return 
		}
		c.String(http.StatusOK,"input data: %v",m["user"])
	})
	g.Run(":9000")
}

If you use c.Get, you need to use your c.Set in context

package main

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

func main() {
	g := gin.Default()
	g.GET("/hello", func(c *gin.Context) {
		c.Set("user",999)
		c.String(http.StatusOK,"user id: %d",c.GetInt("user"))
	})
	g.Run(":9000")
}