1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- package utils
- import (
- "bytes"
- "github.com/gin-gonic/gin"
- "io/ioutil"
- "net/url"
- "strconv"
- )
- // 同时从querystring和body里取参数
- func GetArgument(c *gin.Context, key string, defaultValue string) string {
- v := c.Query(key)
- if v != "" {
- return v
- }
- if c.Request.Body == nil {
- return defaultValue
- }
- body, _ := c.GetRawData()
- c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
- bodyArgs, err := url.ParseQuery(string(body))
- if err != nil {
- return defaultValue
- }
- v = bodyArgs.Get(key)
- if v != "" {
- return v
- }
- return defaultValue
- }
- // 同时从querystring和body里取参数
- func GetIntArgument(c *gin.Context, key string, defaultValue int64) int64 {
- v := c.Query(key)
- if v != "" {
- intV, err := strconv.ParseInt(v, 10, 64)
- if err != nil {
- return defaultValue
- }
- return intV
- }
- if c.Request.Body == nil {
- return defaultValue
- }
- body, _ := c.GetRawData()
- // 写回去, 不然下一次就读取不到了
- c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
- bodyArgs, err := url.ParseQuery(string(body))
- if err != nil {
- return defaultValue
- }
- v = bodyArgs.Get(key)
- if v != "" {
- intV, err := strconv.ParseInt(v, 10, 64)
- if err != nil {
- return defaultValue
- }
- return intV
- }
- return defaultValue
- }
|