Go Http Post request with basic auth and formvalue
Asked Answered
S

1

11

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?

Sech answered 15/6, 2014 at 14:20 Comment(0)
E
28

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
}
Elsaelsbeth answered 15/6, 2014 at 14:49 Comment(3)
Good catch @collinglass, for some reason I thought url.Values had a .String() func.Elsaelsbeth
adding req.Header.Add("Content-Type", "application/x-www-form-urlencoded") will help if you post Form :)Savoie
@Savoie I knew that something was missing somewhere :-) (note: http.PostForm adds that header by default, but NewRequest()...Do() does not). Also, consider using http.MethodPost instead of the literal "POST".Diplococcus

© 2022 - 2024 — McMap. All rights reserved.