Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go Http Post request with basic auth and formvalue

Tags:

http

go

wrapper

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?

like image 831
collinglass Avatar asked Jun 15 '14 14:06

collinglass


1 Answers

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
}
like image 137
OneOfOne Avatar answered Oct 25 '22 16:10

OneOfOne