tips:
- To get queryString we often use GET request
-
go mod tidy
It can analyze the third-party packages that the code depends on, and then record these in go.mod.
For example: to get Yang Chaoyue in the query field:
http://127.0.0.1:9090/web?query=杨超越
Method 1: Query
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/web", func(c *gin.Context) {
//这里要获取浏览器那边发请求携带的query string参数
name := c.Query("query")
c.JSON(http.StatusOK, gin.H{
"name": name,
})
})
r.Run(":9090")
}
The test results are as follows:
Method 2: DefaultQuery
This is actually similar to method 1, the difference is that if no data is queried, you can use the set default data:
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/web", func(c *gin.Context) {
//这里要获取浏览器那边发请求携带的query string参数
//name := c.Query("query")
name := c.DefaultQuery("query", "someone")
c.JSON(http.StatusOK, gin.H{
"name": name,
})
})
r.Run(":9090")
}
The test results are as follows:
Method 3: GetQuery
This function has two return values, which is actually an extra bool value. If the parameter cannot be reached, the second one returns false:
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/web", func(c *gin.Context) {
//这里要获取浏览器那边发请求携带的query string参数
//name := c.Query("query")
//name := c.DefaultQuery("query", "someone")
name, ok := c.GetQuery("query")
if !ok {
name = "someone"
}
c.JSON(http.StatusOK, gin.H{
"name": name,
})
})
r.Run(":9090")
}
I think the third method is more comprehensive and I prefer to use it. Of course, the other two methods can also be used in suitable scenarios.
Reference: bilibili
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。