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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?