Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Saturday, April 15, 2023

How to Make HTTP Requests in Golang

 we will explain how to make HTTP Requests in Golang.

There are net/http package is available to make HTTP requests. We just need tp import the package in our script and can use GET, POST, PostForm HTTP functions to make requests.

So here in this tutorial we will explain how to make GET, POST, PostForm HTTP requests in Golang.

 

1. HTTP GET Request

We can make the simple HTTP GET request using http.Get function. We will import the net/http package and use http.Get function to make request.

Here in this example, we will make the HTTP GET request and get response. We will read the response and display response output.

package main

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

func main() {

    response, err := http.Get("https://api.github.com/users/mojombo")
    if err != nil {
        print(err)
    }  
	
    defer response.Body.Close()
	
    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        print(err)
    }
    
    fmt.Print(string(body))
	
}

Output:

{
	"login":"mojombo",
	"id":1,
	"node_id":"MDQ6VXNlcjE=",
	"avatar_url":"https://avatars0.githubusercontent.com/u/1?v=4",
	"gravatar_id":"",
	"url":"https://api.github.com/users/mojombo",
	"html_url":"https://github.com/mojombo",
	"followers_url":"https://api.github.com/users/mojombo/followers",
	"following_url":"https://api.github.com/users/mojombo/following{/other_user}",
	"gists_url":"https://api.github.com/users/mojombo/gists{/gist_id}",
	"starred_url":"https://api.github.com/users/mojombo/starred{/owner}{/repo}",
	"subscriptions_url":"https://api.github.com/users/mojombo/subscriptions",
	"organizations_url":"https://api.github.com/users/mojombo/orgs",
	"repos_url":"https://api.github.com/users/mojombo/repos",
	"events_url":"https://api.github.com/users/mojombo/events{/privacy}",
	"received_events_url":"https://api.github.com/users/mojombo/received_events",
	"type":"User",
	"site_admin":false,
	"name":"Tom Preston-Werner",
	"company":null,
	"blog":"http://tom.preston-werner.com",
	"location":"San Francisco",
	"email":null,
	"hireable":null,
	"bio":null,
	"twitter_username":null,
	"public_repos":61,
	"public_gists":62,
	"followers":22047,
	"following":11,
	"created_at":"2007-10-20T05:24:19Z",
	"updated_at":"2020-07-07T16:50:36Z"
}

2. HTTP POST Request

We need to import the net/http package for making HTTP request. Then we can use the http.Post function to make HTTP POST requests.

Here in this example, we will make HTTP POST request to https://httpbin.org/post website and send the JSON payload. We will marsh marshaling a map and will get the []byte if successful request. We will handle the error and then make POST request using http.Post. Then we will read the response and display.

No comments:

Post a Comment