Golang: Http Get Request example

Go standard library comes with "net/http" package which has excellent support for  HTTP Client and Server.  
In this example we will be using "http.Get" method to execute Http Get method. We will convert the response to String and print it.

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main(){

	//Use get method to hit the rest API
	resp, err := http.Get("https://reqres.in/api/users/2")

	// An error is returned if there were too many redirects
	// or if there was an HTTP protocol error
	if err != nil {
		panic(err)
	}
	//Need to close the response stream, once response is read.
	//Hence defer close. It will automatically take care of it.
	defer resp.Body.Close()

	//Check response code, if ok then read response.
	if resp.StatusCode == http.StatusOK {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			//Failed to read response.
			panic(err)
		}

		//Convert bytes to String and print
		jsonStr := string(body)
		fmt.Println("Response: ", jsonStr)

	} else {
		//The status is not ok. print the error.
		fmt.Println("Get failed with error: ", resp.Status)
	}
}
Its simple and easy to implement.

No comments:

Post a Comment

Golang: Http POST Request with JSON Body example

Go standard library comes with "net/http" package which has excellent support for HTTP Client and Server.   In order to post JSON ...