Go Http Post request with basic auth and formvalue

14,064

From http://golang.org/pkg/net/http/#Request

// Form contains the parsed form data, including both the URL
// field's query parameters and the POST or PUT form data.
// This field is only available after ParseForm is called.
// The HTTP client ignores Form and uses Body instead.
Form url.Values

You have to pass your url.Values to the request's body instead.

func NewFoo(name string) string {
    client := &http.Client{}
    URL := HOST + "foo/"
    v := url.Values{}
    v.Set("name", name)
    //pass the values to the request's body
    req, err := http.NewRequest("POST", URL, strings.NewReader(v.Encode()))
    req.SetBasicAuth(EMAIL, PASSWORD)
    resp, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    bodyText, err := ioutil.ReadAll(resp.Body)
    s := string(bodyText)
    return s
}
Share:
14,064
collinglass
Author by

collinglass

One of the founders of GamerBet

Updated on June 04, 2022

Comments

  • collinglass
    collinglass almost 2 years

    I am writing a wrapper for an API in go. The api uses basic auth and then POST request requires PostForm value. I'm doing something like this:

    func NewFoo(name string) string {
        client := &http.Client{}
        URL := HOST + "foo/"
        req, err := http.NewRequest("POST", URL, nil)
        v := url.Values{}
        v.Set("name", name)
        req.Form = v
        req.SetBasicAuth(EMAIL, PASSWORD)
        resp, err := client.Do(req)
        if err != nil {
            log.Fatal(err)
        }
        bodyText, err := ioutil.ReadAll(resp.Body)
        s := string(bodyText)
        return s
    }
    

    I had a similar, GET request without the form value and it works. When I run it, it tells me that the "name" value is required. (so it's not getting it)

    Is there any reason this does not work?