douchuanhan8384 2017-10-05 19:15
浏览 51
已采纳

在GO中获得具有基本身份验证的http发布

I have a standard piece of go http request that I am trying to get right in the code below.

func IssueSearchQuery(conf Config) (string, error) {

    tr := &http.Transport{
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }

    var client = &http.Client{
        Timeout:   time.Second * 60,
        Transport: tr,
    }
    URL := conf.URL + "/api/search"
    v := url.Values{}
    v.Set("query_expression", "select * from test")
    req, err := http.NewRequest("POST", URL, 
        bytes.NewBufferString(v.Encode()))

    req.SetBasicAuth(conf.User, conf.Password)
    resp, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    bodyText, err := ioutil.ReadAll(resp.Body)
    s := string(bodyText)
    return s, err
}

In the above code, I am connecting to the server, basic authentication works, but the server responds complaining saying the required query_expression query parameter is missing. If I do curl -u user:pass -d "query_expression=select * from test" --insecure -XPOST 'https://ip:port/api/search' the server responds with the required result.

The code also works if I don't use url.Values{} and instead manually encode my query into the url like URL := conf.URL + "/api/ariel/searches?query_expression=select%20*20from%20test"

I am not able to figure out what I am doing wrong with my query parameters. Can someone help? Thanks!

  • 写回答

1条回答 默认 最新

  • doubi3929 2017-10-05 19:24
    关注

    You appear to be trying to set the POST body to the url-encoded values. Either set your Content-Type header to application/x-www-form-urlencoded, and put them in the body as you're doing (thanks @hobbs), or use your url-encoded values in the actual url rather than the body:

    u, err := url.Parse(conf.URL + "/api/search")
    v := url.Values{}
    v.Set("query_expression", "select * from test")
    u.RawQuery = v.Encode()
    req, err := http.NewRequest("POST", u.String(), nil)
    

    Typically people expect POST data to be in the body, so just adding the req.Header.Set("Content-Type", "application/x-www-form-urlencoded") is probably the best.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c