Golang 容器和不同header的解析

  记录一下,用golang实现一个静态资源容器,膜拜下强人  

http.Handle("/", http.FileServer(http.Dir(currentPath+"/static/")))

非常好用,有机会,试一下其他的框架

PS,Golang对于不同header的解析方法不一样啊……
在这里做个总结记录一下:
1. 普通的表单提交
// ParseForm populates r.Form and r.PostForm.
// For other HTTP methods, or when the Content-Type is not
// application/x-www-form-urlencoded, the request Body is not read, and
// r.PostForm is initialized to a non-nil, empty value.
 
 
func (r *Request) ParseForm() error 

先使用 ParseForm()解析 request 后,再读取参数(application/x-www-form-urlencoded

2. 传文件使用的表单提交
multipart/form-data
同样是表单提交,解析 request 的方式和 application/x-www-form-urlencoded 完全不一样,也是本次开发踩的印象最深的坑。
如果要获取 form-data 中的参数,在已知 key 的情况下,
code = r.FormValue("code")

3. application/json
和1一样是最常用,贴在这里做个记录:
    err := json.NewDecoder(r.Body).Decode(m)
    if nil != err {
        w.WriteHeader(400)
        logs.Error("Illegal params: ", m)
    }
定义出 json 串的结构体,一个key都不能少,就可以通过 Decoder 获取参数了

4. 发表单请求比较优雅的方式:
    param := url.Values{}
 
 
    param.Set("client_id", clientId)
    param.Set("client_secret", clientSecret)
    param.Set("grant_type", grantType)
    param.Set("code", code)
    param.Set("response_type", "code")
    param.Set("redirect_uri", redirectUri)
 
 
    fmt.Println(param)
    logs.Debug("The params is ", param)
 
 
    req, err := http.NewRequest("POST", passportUrl, bytes.NewBufferString(param.Encode()))
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")



转载于:https://www.cnblogs.com/spillage/p/7119587.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值