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 body during post request, we need to convert the data to byte array format and send it along with the request.
You can convert the JSON to a byte array using "encoding/json" package. Then use the NewBuffer method to pass this byte array to the post method.

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

//If the struct variable names does not match with json attributes 
//then you can define the json attributes actual name after json:attname as shown below. 
type User struct {
	Name string  	`json:"name"`
	Job string 	`json:"job"`
}

func main(){

	//Create user struct which need to post.
	user := User{
		Name: "Test User",
		Job: "Go lang Developer",
	}

	//Convert User to byte using Json.Marshal
	//Ignoring error to
	body, _ := json.Marshal(user)

	//Pass new buffer for request with URL to post.
	resp, err := http.Post("https://reqres.in/api/users", "application/json", bytes.NewBuffer(body) )

	// 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 New user is created then read response.
	if resp.StatusCode == http.StatusCreated {
		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 Created. print the error.
		fmt.Println("Get failed with error: ", resp.Status)
	}
}

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.

Golang: Reading environment variables

Usually, environment variables are used to provide the configuration information for the program. You can set the environment outside of the program and you can assess these during execution. Go provides the simplest mechanism to access the environment variables. 
You can use 'OS' package to get or set the environment variables.

package main

import (
	"fmt"
	"os"
	"strings"
)

func main() {
	//Read single environment variable value
	val := os.Getenv("WORKING_DIR")
	//Check if the value is set.
	if val != "" {
		fmt.Println("Working Dir is: ", val )
	} else {
		fmt.Println("Working Dir is not set. Setting it now.")
		//You can set env variable using setEnv method.
		os.Setenv("WORKING_DIR", "/root/app_dir")
		fmt.Println("Working Dir is: ", os.Getenv("WORKING_DIR") )
	}

	//You can also iterate over all the environment variables.
	//Here environment variables are returned as string containing varname=value form
	for _, varNVal := range os.Environ() {
		keyVal := strings.SplitN(varNVal, "=", 2)
		fmt.Println("Variable name: " + keyVal[0] + "\tValue: " + keyVal[1] )
	}
}

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 ...