How to send a POST request in Go?

前端 未结 2 1066
走了就别回头了
走了就别回头了 2020-12-13 01:12

I am trying to make a POST request but I can\'t get it done. Nothing is received on the other side.

Is this how it is supposed to work? I\'m aware of the PostForm fu

相关标签:
2条回答
  • 2020-12-13 01:58

    I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.

    //one-line post request/response...
    response, err := http.PostForm(APIURL, url.Values{
        "ln": {c.ln},
        "ip": {c.ip},
        "ua": {c.ua}})
    
    //okay, moving on...
    if err != nil {
      //handle postform error
    }
    
    defer response.Body.Close()
    body, err := ioutil.ReadAll(response.Body)
    
    if err != nil {
      //handle read response error
    }
    
    fmt.Printf("%s\n", string(body))
    

    https://golang.org/pkg/net/http/#pkg-overview

    0 讨论(0)
  • 2020-12-13 02:09

    You have mostly the right idea, it's just the sending of the form that is wrong. The form belongs in the body of the request.

    req, err := http.NewRequest("POST", url, strings.NewReader(form.Encode()))
    
    0 讨论(0)
提交回复
热议问题