美文网首页
golang http 客户端

golang http 客户端

作者: Newzer | 来源:发表于2022-08-26 15:40 被阅读0次

    http 发送post 请求, 发送数据格式用application/json,
    发送参数必须写到buffer 缓冲器里,返回数据也从从缓冲区拿数据
    url := "http://127.0.0.1:8084/api/silent/giftCodeAdd"
    body := map[string]interface{}{"activity_id":params.ActivityId, "count":params.Count}
    byteData, err := json.Marshal(body)

    if err != nil {
        ret := map[string]string{"code": "-2", "msg": "服务器错误"}
        appG.Response(e.INVALID_PARAMS, ret)
        return
    }
    
    reader := bytes.NewBuffer(byteData)
    response,err := http.Post(url, "application/json; charset=utf-8", reader)
    defer response.Body.Close()
    logging.Info("byteData:", byteData)
    logging.Info("send to url:", url, "body:", body, "response:", response, "err:", err)
    if err != nil{
        ret := map[string]string{"code": "-2", "msg": "服务器错误"}
        appG.Response(e.INVALID_PARAMS, ret)
        return
    }
    
    if response.StatusCode == http.StatusOK {
        appG.Response(e.SUCCESS,"success")
        return
    }
    
    resbody := response.Body
    logging.Info("response body is", resbody)
    
    content, err := ioutil.ReadAll(resbody)
    if err != nil {
        ret := map[string]string{"code": "-2", "msg": "服务器错误"}
        appG.Response(e.INVALID_PARAMS, ret)
        return
    }
    var m  map[string]interface{}
    err = json.Unmarshal(content, &m)
    if err != nil {
        ret := map[string]string{"code": "-2", "msg": "服务器错误"}
        appG.Response(e.INVALID_PARAMS, ret)
        return
    }
    logging.Info("m:", m)
    appG.Response(e.INVALID_PARAMS, m)

    相关文章

      网友评论

          本文标题:golang http 客户端

          本文链接:https://www.haomeiwen.com/subject/rudomrtx.html