使用基本身份验证和formvalue转到Http Post请求

时间:2014-06-15 14:20:58

标签: http go wrapper

我正在编写一个API的包装器。 api使用基本身份验证,然后POST请求需要PostForm值。我正在做这样的事情:

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
}

我有一个类似的,没有表单值的GET请求,它有效。当我运行它时,它会告诉我" name"值是必需的。 (所以它没有得到它)​​

有什么理由不起作用吗?

1 个答案:

答案 0 :(得分:15)

来自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

您必须将url.Values传递给请求的正文。

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
}