Sobes.tech
Senior

Can the structure be used for HTTP request parameters?

sobes.tech AI

Answer from AI

Yes, in Go, a struct can be used for HTTP request parameters, especially when working with frameworks or libraries that support automatic binding of request parameters to struct fields.

For example, if you have a struct with url or form tags, you can automatically parse GET or POST request parameters into this struct:

 type Params struct {
     UserID   string `url:"user_id"`
     Page     int    `url:"page"`
 }

 func handler(w http.ResponseWriter, r *http.Request) {
     var p Params
     // Using, for example, github.com/gorilla/schema for decoding
     decoder := schema.NewDecoder()
     err := decoder.Decode(&p, r.URL.Query())
     if err != nil {
         http.Error(w, err.Error(), http.StatusBadRequest)
         return
     }
     // Now p contains the request parameters
 }

Thus, a struct helps to work with HTTP request parameters conveniently and type-safely.