Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

temoto commented Jan 12, 2019

Thank you. 👍

@artinu777

This comment has been minimized.

Copy link

artinu777 commented Feb 25, 2019

Thank you

@deepakjacob

This comment has been minimized.

Copy link

deepakjacob commented Jul 24, 2019

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

@jdr430

This comment has been minimized.

Copy link

jdr430 commented Aug 15, 2019

Thank you!!

@KanybekMomukeyev

This comment has been minimized.

Copy link

KanybekMomukeyev commented Dec 4, 2019

Very helpfull!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.