Skip to content

Instantly share code, notes, and snippets.

@17twenty
Created February 22, 2016 01:04
Show Gist options
  • Save 17twenty/2fb30a22141d84e52446 to your computer and use it in GitHub Desktop.
Save 17twenty/2fb30a22141d84e52446 to your computer and use it in GitHub Desktop.
POST with NewRequest using Golang
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
)
const (
clientSecret string = "9ca19353e1fb861f6d3aed8af6803c0b"
accessToken string = "d42cd44868d2fe953329677aa1c71e1d80f0f4d7"
siteHost string = "http://coop.apps.knpuniversity.com"
userID string = "460"
)
func main() {
client := &http.Client{}
data := url.Values{}
data.Set("client_id", `Lazy Test`)
data.Add("client_secret", clientSecret)
data.Add("grant_type", "client_credentials")
req, err := http.NewRequest("POST", fmt.Sprintf("%s/token", siteHost), bytes.NewBufferString(data.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value") // This makes it work
if err != nil {
log.Println(err)
}
resp, err := client.Do(req)
if err != nil {
log.Println(err)
}
f, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println(err)
}
resp.Body.Close()
if err != nil {
log.Fatal(err)
}
fmt.Println(string(f))
}
@temoto
Copy link

temoto commented Jan 12, 2019

Thank you. 👍

@artinu777
Copy link

Thank you

@deepakjacob
Copy link

deepakjacob commented Jul 24, 2019

Yes, without Content-Type http.NewRequest('POST', url, body) won't work....

@jdr430
Copy link

jdr430 commented Aug 15, 2019

Thank you!!

@KanybekMomukeyev
Copy link

Very helpfull!

@trcamaraps
Copy link

Thank you!!

@rootshaxor
Copy link

Thanks

@dgsfor
Copy link

dgsfor commented Dec 1, 2020

if post data has int type,the "data := url.Values{}" cannot be used

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment