Unleashing the Power of Go: Ultimate Guide to Effective URL Handling with Golang

Unleashing the Power of Go: Ultimate Guide to Effective URL Handling with Golang

·

5 min read

URLs and HTTP

HTTP requests are the most basic part of the web as a whole. They are used to access the resources that are hosted in the remote servers. HTTP stands for hypertext transfer protocol that ensures the transfer of data between a client and a server. It works when we open up our browser and type an URL and the browser fetches all the information from the server which is also known as HTTP client-server interaction.

In web apps, it's very common to fetch data using APIs so when you are building a website you need to set up an HTTP client within your application so to make all these happen.

We can make HTTP requests in many programming languages. Below this, I will show you how to make an HTTP request in Go.

Making HTTP requests in Go

GET request

The first request we will make is an HTTP GET request using GET you can get your desired data from a specific source. The GET method is used to fetch data from the server.

The first step of making a GET request in Go is to import the net/http package from the standard library This package provides us with all the utilities we need to make HTTP requests with ease. We can import the net/http package and other packages we will need by adding the following lines of code to a main.go file that we create:

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

The Get function takes in a URL and returns a response of type pointer to a struct and an error.

resp, err := http.Get("https://jsonplaceholder.typicode.com/posts/1")
if err != nil {
   log.Fatalln(err)
}

To make the request, we invoke the Get function, passing in a URL string (https://jsonplaceholder.typicode.com/posts) as seen above. The values returned from the invocation of this function are stored in two variables typically called resp and err. Although the variable resp contains our response, if we print it out we would get a load of incoherent data which includes the header and properties of the request made. To get the response we are interested in, we have to access the Body property on the response struct and read it before finally printing it out to the terminal. We can read the response body using the ioutil.ReadMe function.

Similar to the Get function, the ioutil.ReadMe the function returns a body and an error. It is important to note that the response Body should be closed after we are done reading from it to prevent memory leaks.

The defer keyword which executes resp.Body.Close() at the end of the function is used to close the response body. We can then go ahead and print out the value of the response to the terminal. As good programmers, it is important to handle possible errors, so we use an if statement to check for any errors and log the error if it exists:

package main

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

func main() {
   resp, err := http.Get("https://jsonplaceholder.typicode.com/posts")
   if err != nil {
      log.Fatalln(err)
   }
//We Read the response body on the line below.
   body, err := ioutil.ReadAll(resp.Body)
   if err != nil {
      log.Fatalln(err)
   }
//Convert the body to type string
   sb := string(body)
   log.Printf(sb)
}

POST request

The HTTP POST method is utilized for making requests that typically include a body. Its primary purpose is to transmit data to a server, with the sent data commonly employed for resource creation or update.

A prime example of a POST request occurs when a user attempts to create a social media account. In this scenario, the user must furnish their information such as name, email, and password. This data is subsequently extracted and transmitted to the server as a POST request, which then proceeds to create and store the user's account. Similar to the aforementioned GET method, Go's net/http package facilitates the execution of POST requests via the Post function. This function necessitates three parameters.

  1. The URL address of the server

  2. The content type of the body as a string

  3. The request body that is to be sent using the POST method of type io.Reader

The Post function returns a response and an error. For us to invoke the Post function we have to convert our request body to the accepted type. For this example, we will make a post request to https://postman-echo.com/post and pass in JSON data containing a name and an email. To get started we convert our JSON data to a type that implements the Io. Reader interfaces the Post function expects, this is a two-way step:

  • The first step is to encode our JSON data so it can return data in byte format, to do this we use the Marshall function Go’s JSON package provides

  • Next, we convert the encoded JSON data to a type implemented by the io.Reader interface, we simply use the NewBuffer function for this, passing in the encoded JSON data as an argument. The NewBuffer function returns a value of type buffer which we can then pass unto the Post function.

postBody, _ := json.Marshal(map[string]string{
   "name":  "Toby",
   "email": "Toby@example.com",
})
responseBody := bytes.NewBuffer(postBody)

Once we have gathered all the necessary parameters for the Post function, we can proceed by invoking it. We will pass the following values as arguments: the URL string "postman-echo.com/post", the content type "application/JSON", and the request body obtained from the NewBuffer function. The response from the Post function will be assigned to variables resp and err, representing the response and potential errors, respectively. After handling any errors, we will proceed to read and print the response body, just as we did with the Get function in the previous section. At this stage, your file should resemble the following code snippet:

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

func main() {
//Encode the data
   postBody, _ := json.Marshal(map[string]string{
      "name":  "Toby",
      "email": "Toby@example.com",
   })
   responseBody := bytes.NewBuffer(postBody)
//Leverage Go's HTTP Post function to make request
   resp, err := http.Post("https://postman-echo.com/post", "application/json", responseBody)
//Handle Error
   if err != nil {
      log.Fatalf("An Error Occured %v", err)
   }
   defer resp.Body.Close()
//Read the response body
   body, err := ioutil.ReadAll(resp.Body)
   if err != nil {
      log.Fatalln(err)
   }
   sb := string(body)
   log.Printf(sb)
}

Conclusion

In this article, we discussed how to make HTTP requests in Go. I highly recommend checking out the source code and documentation of the net/http package to explore the other amazing functionalities it provides.