Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the binding request string / URI/ request header / check box / form type in the Golang GinWeb framework

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains the "Golang GinWeb framework how to understand the binding request string / URI/ request header / check box / form type", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in-depth, together to study and learn "Golang GinWeb framework how to understand binding request string / URI/ request header / check box / form type"!

Bind only query strings

Use the SholdBindQuery method to bind only query parameters, not post data.

The following is the sample code and the simulation test request:

Package main import ("log"github.com/gin-gonic/gin") type Person struct {Name string `form: "name" `Address string `form: "address" `} func main () {route: = gin.Default () route.Any ("/ testing", startPage) route.Run (": 8085")} func startPage (c * gin.Context) {var person Person / / ShouldBindQuery is a shortcut for c.ShouldBindWith (obj) Binding.Query) / / ShouldBindQuery is a quick binding method of the c.ShouldBindWith (obj, binding.Query) method, which binds only the request string query string and ignores the form data submitted by Post if c.ShouldBindQuery (& person) = = nil {log.Println ("= Only Bind By Query String =") log.Println (person.Name) log.Println (person.Address)} c.String "Success")} / / only bind query simulate query string request / / curl-X GET "localhost:8085/testing?name=eason&address=xyz" / / only bind query string, ignore form data simulate query string request and Post form, the form here will be ignored / / curl-X POST "localhost:8085/testing?name=eason&address=xyz"-- data 'name=ignore&address=ignore'-H "Content-Type:application/x-www-form-urlencoded

Bind query string or Post data (form)

Code and request examples:

Package main import ("log"time"github.com/gin-gonic/gin") type Person struct {Name string `form: "name" `Address string `form: "address" `Birthday time.Time `form: "birthday" time_format: "2006-01-02" time_utc: "1" `CreateTime time.Time `form: "createTime" time_format: "unixNano" `UnixTime time.Time `form: "unixTime" time_format : "unix" `} func main () {route: = gin.Default () / route.GET ("/ testing" StartPage) / / use GET route.POST ("/ testing", startPage) / / use POST route.Run (": 8085")} func startPage (c * gin.Context) {var person Person / / If `GET`, only `Form` binding engine (`query`) used. If the route is a GET method, only use query string engine to bind / / If `POST`, first checks the `content- type` for `JSON` or `XML`, then uses `Form` (`form- data`). / / See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L48 / / if in POST mode, the ShouldBind method checks the request type header Content-Type to automatically select the binding engine For example, Json/XML if c.ShouldBind (& person) = = nil {log.Println (person.Name) log.Println (person.Address) log.Println (person.Birthday) log.Println (person.CreateTime) log.Println (person.UnixTime)} / / if c.BindJSON (& person) = nil {/ / log.Println ("= Bind By JSON =") / log.Println (person.Name) / / Log.Println (person.Address) / /} c.String "Success")} / / simulated query string parameter request: / / curl-X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033" / / simulated Post Json request / / curl-X POST localhost:8085/testing-- data'{"name": "JJ", "address": "xyz"}'- H "Content-Type:application/json"

Bind URI

Bind the fields specified by the tags in the structure to the corresponding fields in the URI. For more information, please see: https://github.com/gin-gonic/gin/issues/846

Code and request examples:

Package main import "github.com/gin-gonic/gin" type Person struct {ID string `uri: "id" binding: "required,uuid" `/ specify the URI tag Name string `uri: "name" binding: "required"`} func main () {route: = gin.Default () / the name and id in URI below correspond to route.GET ("/: name/:id"), respectively. Func (c * gin.Context) {var person Person if err: = c.ShouldBindUri (& person) Err! = nil {c.JSON (400, gin.H {"msg": err}) return} c.JSON (200,200, gin.H {"name": person.Name, "uuid": person.ID}) route.Run (": 8088")} / / curl-v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3 / / curl-v localhost:8088/thinkerou/not-uuid

Bind request header

Bind the information in the request header to the structure

Package main import ("fmt"github.com/gin-gonic/gin") type testHeader struct {Rate int `header: "Rate" `/ / add the header tag Domain string `header: "Domain"`} func main () {r: = gin.Default () r.GET ("/", func (c * gin.Context) {h: = testHeader {} / / ShouldBindHeader is c.ShouldBindWith (obj) Shortcut method if err: = c.ShouldBindHeader (& h) for binding.Header) Err! = nil {c.JSON (200, err)} fmt.Printf ("% # v\ n", h) c.JSON (200, gin.H {"Rate": h.Rate "Domain": h.Domain}) r.Run ()} / / Simulation request / / curl-H "rate:300"-H "domain:music" http://localhost:8080/ reference output: / / {"Domain": "music", "Rate": 300}

Bind HTML check box

Put html and main.go in the same directory. After running go run main.go, visit http://localhost:8080, and check the check box, then submit the test.

Main.go

Package main import ("github.com/gin-gonic/gin") type myForm struct {Colors [] string `form: the colors [] array slice in the tag "colors []" `/ / corresponds to the name= "colors []" in the html file} func main () {r: = gin.Default () / / LoadHTMLGlob matches the HTML file in wildcard mode and renders the content Provide the front end access to r.LoadHTMLGlob ("* .html") r.GET ("/", indexHandler) r.POST ("/", formHandler) r.Run (": 8080")} func indexHandler (c * gin.Context) {c.HTML (200, "form.html", nil)} func formHandler (c * gin.Context) {var fakeForm myForm c.Bind (& fakeForm) / / Bind method according to the request header type Content-Type Automatically select the appropriate binding engine, such as Json/XML c.JSON (200,200, gin.H {"color": fakeForm.Colors})} / / put html and main.go in the same directory. After running go run main.go, visit http://localhost:8080, and check the check box, then submit the test.

Form.html

Check some colors

Red Green Blue

Bind Multipart/Urlencoded

Bind the multi-part type form data multipart/form-data or URL encoded type form application/x-www-form-urlencoded data using the ShouldBind method combined with the structure tag and the mime/multipart package:

Package main import ("github.com/gin-gonic/gin"mime/multipart"net/http") type ProfileForm struct {Name string `form: "name" binding: "required" `Avatar * multipart.FileHeader `form: "avatar" binding: "required"` / / or for multiple files / / Avatars [] * multipart.FileHeader `form: "avatar" binding: "required" `} func main () {router: = gin. Default () router.POST ("/ profile" Func (c * gin.Context) {/ / you can bind multipart form with explicit binding declaration: you can use the ShouldBindWith (& from, binding.Form) method to bind the multi-part type form multipart form / / c.ShouldBindWith (& form) Binding.Form) / / or you can simply use autobinding with ShouldBind method: var form ProfileForm / / in this case proper binding will be automatically selected / / here use the ShouldBind method to automatically select the binder for binding if err: = c.ShouldBind (& form) Err! = nil {c.String (http.StatusBadRequest, "bad request") return} / / Save the uploaded form file to the specified target file err: = c.SaveUploadedFile (form.Avatar, form.Avatar.Filename) if err! = nil {c.String (http.StatusInternalServerError, "unknown error") return} / / db.Save (& form) c.String (http.StatusOK) "ok")}) router.Run (": 8080")} / / Simulation Test: / / curl-X POST-v-- form name=user-- form "avatar=@./avatar.png" http://localhost:8080/profile Thank you for your reading The above is the "Golang GinWeb framework how to understand the binding request string / URI/ request header / check box / form type" content, after the study of this article, I believe you on the Golang GinWeb framework how to understand the binding request string / URI/ request header / check box / form type of this problem has a more profound understanding, the specific use of the situation also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report