APi not getting called in Golang but works fine in postman

i have an api "http://someurl /v1.2/auth/token/get"
Header:
Authorization basic xxxxxxxxxxxxxxxx
Content-Type application/json
Body:
{
“grant_type”: “client_credentials”
}
this is a post request i am able to call the same in Postman but in Golang i am not able to call the same api , what can be the possible reason for this .
thanks

Please include the relevant parts of your Go code that you use to make this request.

What is the result? Do you get any errors?

Hi Iutzhorn san,
i get the following
error response from url &{401 Unauthorized 401 HTTP/1.1 1 1 map[Content-Type:[application/json; charset=utf-8] Cache-Control:[no-cache] X-Xss-Protection:[1;mode=block] Via:[1.1 google] Server:[nginx/1.13.5] Date:[Tue, 01 May 2018 07:24:39 GMT] Content-Length:[66] Www-Authenticate:[basic, bearer] Pragma:[no-cache] X-Content-Type-Options:[nosniff]] 0xc420092380 66 [] false false map[] 0xc4201b4000 }
error while getting response from url

else if auth == client_id {

		formData := url.Values{
			"Authorization": {"Basic xxxxxxxxxxxx"},
			"grant_type": {"client_credentials"},

		}
		resp, err := http.PostForm("http://=sample/v1.2/auth/token/get",formData)
		fmt.Println("response from url",resp)

Your Go code puts both Authorization and grant_type into one url.Values instance which is then encoded as application/x-www-form-urlencoded by http.PostForm. That is different from what you describe above where Authorization is a header and the body is encoded as application/json.

Try to use http.NewRequest like this (not tested):

package main

import (
	"fmt"
	"log"
	"net/http"
	"strings"
)

func main() {
	client := &http.Client{}
	body := strings.NewReader("{\"grant_type\": \"client_credentials\"")
	req, err := http.NewRequest("POST", "https://www.httpbin.org/post", body)
	if err != nil {
		log.Panic(err)
	}
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Authorization", "Basic xxxxxxxxxxxxxxxx")
	resp, err := client.Do(req)
	if err != nil {
		log.Panic(err)
	}
	fmt.Println(resp.Status)
}

i am still getting an error panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0x25706b]

goroutine 1 [running]:
main.main()
/tmp/sandbox814824644/main.go:21 +0x22b
thank you for your kind help .

What does line 21 of your main.go do?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.