Why am I not getting JSON response from GitHub?

Here is my code:

func AuthGitHub() error {
	postBody, _ := json.Marshal(map[string]string{
		"client_id": "XXXX",
		"scope": "repo gist user",
	})
	responseBody := bytes.NewBuffer(postBody)

	req, err := http.NewRequest("POST", "https://github.com/login/device/code", responseBody)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("User-Agent", "Blah/0.1")
	if err != nil {
		return err
	}

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	fmt.Println(body)
	sb := string(body)
	fmt.Println(sb)
	return nil
}

The docs on the other end says that it would return a JSON.

The response I am getting:

device_code=XXXXX&expires_in=899&interval=5&user_code=XXXX-XXXX&verification_uri=https%3A%2F%2Fgithub.com%2Flogin%2Fdevice

The response I want:

{
  "device_code": "XXXXXX",
  "user_code": "XXXX-XXXX",
  "verification_uri": "https://github.com/login/device",
  "expires_in": 900,
  "interval": 5
}

Am I missing something here?

Instead of JSON, use URL encoding in the body of your request.

EDIT: Oops, I missed something. If you’re getting the response as URL-encoded, can you just decode and turn it into JSON yourself?

You probably need to set the Accept on the request.

Before trying to do it with a Go program, you can test the protocol by using a program like Postman or Insomnia Rest Client that allows you to enter the parameters in a form and see the response.

req.Header.Set("Content-Type", "application/json")

should be

req.Header.Set("Accept", "application/json")

With this configuration, I am getting a {"error":"Not Found"} response.

Content-Type is for what you are sending, Accept is for what you want back.

You probably need both then.

Just a bit of experimentation and documentation reading would have told you this already.

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