Get request parameters

Request parameters in the wego framework can be obtained using a unified Param object, which can obtain the following types of parameters:

  • URL path parameters Path parameters are parameters matched from the Path of the url. Path parameters are usually defined in colon routing or asterisk routing and obtained by matching in the Path of the url request.
  • URL query parameters
    The URL query parameter is the parameter obtained by parsing a string in the form of k1=v1&k2=v2... starting with ? in the URL request.
  • Form parameter
    Form parameters are also called form parameters. The form data here refers to the data that the browser submits the form data to the server through a POST request and is parsed by the server. The Content-Type that the browser will send the POST request with is usually x-www-form-urlencoded or multipart/form-data.

Get the request parameters through the c.Param.GetXXX function in wego:

 func TestGetParam(t *testing.T) {
   web, _ := NewWeb()

   web.GET("/user", func(c *WebContext) {
       name := c.Param.GetString("name")
       if name.Error != nil {
           t.Error(name.Error)
       }

       age := c.Param.GetInt("age")
       if age.Error != nil {
           t.Error(age.Error)
       }

       c.WriteText(200, name.Value)
   })

   w := httptest.NewRecorder()
   req, _ := http.NewRequest("GET", "/user?name=lisi&age=12", nil)
   web.ServeHTTP(w, req)
}

In order to facilitate the acquisition of various types of parameters, wego provides a series of GetXXX functions for parameter acquisition:

  • GetString(key string, defaultValue ...string) ValidString
  • GetBool(key string, defaultValue ...bool) ValidBool
  • GetInt(key string, defaultValue ...int) ValidInt
  • GetInt32(key string, defaultValue ...int32) ValidInt32
  • GetInt64(key string, defaultValue ...int64) ValidInt64
  • GetFloat(key string, defaultValue ...float64) ValidFloat
  • GetTime(key string, format string, defaultValue ...time.Time) ValidTime

The GetXXX function does not directly return a value of type XXX. For example, what GetInt returns is not a value of type int, but a value of type ValidInt:

 type ValidInt struct {
   Value     int
   Error      error
}

Among them, the value of the Value parameter, Error is usually an error that the parameter does not exist, or a type conversion error. For example, when using GetInt(key) to query a parameter, if the specified parameter does not exist, or the parameter cannot be converted to int type, the Value of ValidInt is 0, and the error information is assigned to the Error field of ValidInt.

Using MustXXX Convenience Functions

MustXXX functions directly return the value of the corresponding type, which is more convenient to use. When using the MustXXX function to query parameters, if there is no specified parameter, or there is a type conversion error, and a default value is provided when calling, the default value is returned, otherwise the "0" value of the corresponding type is returned:

  • MustString(key string, defaultValue ...string) string
  • MustBool(key string, defaultValue ...bool) bool
  • MustInt(key string, defaultValue ...int) int
  • MustInt32(key string, defaultValue ...int32) int32
  • MustInt64(key string, defaultValue ...int64) int64
  • MustFloat(key string, defaultValue ...float64) float64
  • MustTime(key string, format string, defaultValue ...time.Time) time.Time

     func TestParamMust(t *testing.T) {
     web, _ := NewWeb()
    
     web.GET("/user", func(c *WebContext) {
         name := c.Param.MustString("name")
         t.Log(name)
         age := c.Param.MustInt("age")
         t.Log(age)
     })
    
     w := httptest.NewRecorder()
     req, _ := http.NewRequest("GET", "/user?name=lisi&age=12", nil)
     web.ServeHTTP(w, req)
    }

Get path parameters

In wego, the path parameters can be obtained through WebContext.RouteParam.GetXXX:

 func TestGetPathParam(t *testing.T) {
   web, _ := NewWeb()

   web.GET("/hello/:id", func(c *WebContext) {
       ret := c.RouteParam.GetString("id")
       if ret.Error != nil {
           t.Error(ret.Error)
       }
       t.Log(ret.Value)
   })

   w := httptest.NewRecorder()
   req, _ := http.NewRequest("GET", "/hello/123", nil)
   web.ServeHTTP(w, req)
}

Get query parameters

Get URL query parameters through WebContext.QueryParam.GetXXX in wego:

 func TestGetQueryParamGet(t *testing.T) {
   web, _ := NewWeb()

   web.GET("/user", func(c *WebContext) {
       name := c.QueryParam.GetString("name").Value
       age := c.QueryParam.GetInt("age").Value
       t.Log(name)
       t.Log(age)
   })

   w := httptest.NewRecorder()
   req, _ := http.NewRequest("GET", "/user?name=lisi&age=12", nil)
   web.ServeHTTP(w, req)
}

Get Form parameters

Use WebContext.FormParam.GetXXX in wego to get Form parameters:

 func TestGetFromParamGet(t *testing.T) {
   web, _ := NewWeb()

   web.POST("/user", func(c *WebContext) {
       name := c.FormParam.GetString("name").Value
       age := c.FormParam.GetInt("age").Value
       t.Log(name)
       t.Log(age)
   })

   var buff bytes.Buffer
   buff.WriteString("name=lisi&age=12")

   w := httptest.NewRecorder()
   req, _ := http.NewRequest("POST", "/user", &buff)
   req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
   web.ServeHTTP(w, req)
}

Bind parameters to Struct

In addition to the parameter acquisition methods listed above, wego also provides a parameter binding method to obtain parameters: use the GetStruct method to directly bind the HTTP request parameters to the struct object. The GetStruct function obtains the value of the request parameter according to the field name of the struct or the tag name of the field. E.g:

  • First define struct

     type FormUser struct {
      Name     string         `form:"name"`
      Age     int
    }
  • Once the FormUser is defined, you can get the form parameters like this:

     func TestGetStruct(t *testing.T) {
     web, _ := NewWeb()
    
     web.POST("/user", func(c *WebContext) {
         var user FormUser
         err := c.Param.GetStruct(&user)
         if err != nil {
             t.Log(err)
         }
         t.Log(user)
     })
    
     var buff bytes.Buffer
     buff.WriteString("name=lisi&Age=12")
    
     w := httptest.NewRecorder()
     req, _ := http.NewRequest("POST", "/user", &buff)
     req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
     web.ServeHTTP(w, req)
    }

Parse Json format Body to Struct

If the format of the Body data in the POST request is in JSON format, you can directly use the ReadJSON() function to read it:

 func TestReadJson(t *testing.T) {
    web, _ := NewWeb()

    web.POST("/user", func(c *WebContext) {
        var user2 User
        err := c.ReadJSON(&user2)
        if err != nil {
            t.Log(err)
        }
        t.Log(user2)
    })

    user := User{}
    user.ID = 1
    user.Name = "demo"
    user.Age = 12
    data, _ := json.Marshal(user)

    w := httptest.NewRecorder()
    req, _ := http.NewRequest("POST", "/user",  bytes.NewBuffer(data))
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    web.ServeHTTP(w, req)
}

Parse XML format Body to Struct

If the format of the Body data in the POST request is in XML format, you can directly use the ReadXML function to read it:

 func TestReadXML(t *testing.T) {
   web, _ := NewWeb()

   web.POST("/user", func(c *WebContext) {
       var user2 User
       err := c.ReadXML(&user2)
       if err != nil {
           t.Log(err)
       }
       t.Log(user2)
   })

   user := User{}
   user.ID = 1
   user.Name = "demo"
   user.Age = 12
   data, _ := xml.Marshal(user)

   w := httptest.NewRecorder()
   req, _ := http.NewRequest("POST", "/user",  bytes.NewBuffer(data))
   req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
   web.ServeHTTP(w, req)
}

Upload file processing

The wego framework provides two very convenient functions to handle uploading files:

  • GetFile(name string) (*multipart.FileHeader, error)

     用于读取表单中的文件信息
  • SaveToFile(fromfile, tofile string) error

     用于实现快速保存文件到本地路径

    Sample code:

     <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>file upload</title>
    </head>
    <body>
    <h1>上传文件</h1>
    <form action="/upload" method="post" enctype="multipart/form-data">
      文件: <input type="file" name="file"><br><br>
      <input type="submit" value="上传文件">
    </form>
    </body>
    </html>
  • server code

     func upload(c *wego.WebContext) {
      fh, err := c.GetFile("file")
      if err != nil {
          log.Error(err)
          c.AbortWithError(500, err)
          return
      }
    
      file, err := fh.Open()
      if err != nil {
          log.Error(err)
          c.AbortWithError(500, err)
          return
      }
      defer file.Close()
    
      data, err := ioutil.ReadAll(file)
      if err != nil {
          log.Error(err)
          c.AbortWithError(500, err)
          return
      }
    
      c.WriteText(200, string(data))
    }

get wego

go get github.com/haming123/wego


haming
4 声望146 粉丝

WEB开发, 服务器端开发, C/C++, Linux/Unix, Golang