Follow

Follow

Headers in go language REST API- Part-3

Maheshwar Ligade's photo
Maheshwar Ligade
·Apr 11, 2023·

5 min read

Play this article

Table of contents

  • What are HTTP Headers?
  • HTTP Request Headers
  • HTTP Response Headers
  • Handling Headers in Go Language REST API
  • Getting Started
  • Adding Headers
  • Accessing Headers
  • Manipulating Headers
  • Conclusion

Headers play an important role in communication between a client and a server. They provide additional information about the request being made or the response being sent. In a Go language-based REST API, headers can be easily accessed and manipulated. In this article, we will explore how to handle headers in a Go language-based REST API.

What are HTTP Headers?

HTTP headers are key-value pairs that are sent between the client and server as a part of the HTTP request or response. The headers contain additional information about the message, such as the type of data that is being sent, the length of the message, and the encoding used. HTTP headers are used by web applications to implement authentication, caching, and other features.

HTTP Request Headers

HTTP request headers are sent by the client to the server in the request message. They provide additional information about the request, such as the type of data that is being sent, the user-agent making the request, and authentication credentials.

Example of HTTP Request Headers:

makefileCopy codeGET / HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Upgrade-Insecure-Requests: 1

HTTP Response Headers

HTTP response headers are sent by the server to the client in the response message. They provide additional information about the response, such as the type of data that is being sent, the length of the message, and caching information.

Example of HTTP Response Headers:

yamlCopy codeHTTP/1.1 200 OK
Date: Sun, 17 Mar 2023 10:20:32 GMT
Server: Apache/2.4.46 (Win64) OpenSSL/1.1.1i PHP/7.3.26
Content-Type: text/html; charset=UTF-8
Content-Length: 155

Handling Headers in Go Language REST API

Go provides built-in support for handling HTTP headers in REST APIs. The http package provides Header struct to work with headers. The Header struct represents the HTTP headers in a key-value format. Here is an example of how to set a response header in a Go REST API:

func handler(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Content-Type", "application/json")
  w.WriteHeader(http.StatusOK)
  fmt.Fprintf(w, `{"message":"Hello, World!"}`)
}

In the above example, we are setting the Content-Type header to application/json using Set() method of Header struct. The WriteHeader() method sets the status code of the response to 200 OK.

Similarly, we can retrieve the headers sent by the client in the request by using Header property of http.Request struct. Here is an example of how to retrieve the User-Agent header from the request:

func handler(w http.ResponseWriter, r *http.Request) {
  user_agent := r.Header.Get("User-Agent")
  fmt.Fprintf(w, `{"user_agent":"%s"}`, user_agent)
}

In the above example, we are retrieving the value of User-Agent header sent by the client using Get() method of Header struct.

Getting Started

Before we dive into handling headers, we need to set up a basic Go language-based REST API. We can create a new project and set up a basic REST API using the following code:

package main

import (
    "encoding/json"
    "log"
    "net/http"
)

type Book struct {
    ID     string `json:"id"`
    Title  string `json:"title"`
    Author string `json:"author"`
}

var books []Book

func main() {
    http.HandleFunc("/books", getBooks)
    http.HandleFunc("/books/", getBookByID)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func getBooks(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(books)
}

func getBookByID(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    id := r.URL.Path[len("/books/"):]
    for _, book := range books {
        if book.ID == id {
            json.NewEncoder(w).Encode(book)
            return
        }
    }
    http.Error(w, "Book not found", http.StatusNotFound)
}

This code sets up a basic REST API that listens on port 8080 and has two endpoints: /books and /books/{id}. The /books endpoint returns a list of all books, and the /books/{id} endpoint returns the book with the specified ID.

Adding Headers

We can add headers to a response using the Header().Set() method of the http.ResponseWriter object. This method takes two arguments: the name of the header and its value. For example, if we want to add a header named "X-MyHeader" with a value of "Hello World", we can modify our getBooks function as follows:

func getBooks(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.Header().Set("X-MyHeader", "Hello World")
    json.NewEncoder(w).Encode(books)
}

This will add the "X-MyHeader" header to the response with a value of "Hello World".

Accessing Headers

We can access headers from a request using the Header.Get() method of the http.Request object. This method takes the name of the header as its argument and returns its value. For example, if we want to access the value of the "Authorization" header, we can modify our getBooks function as follows:

func getBooks(w http.ResponseWriter, r *http.Request) {
    authorizationHeader := r.Header.Get("Authorization")
    // do something with the authorization header
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(books)
}

This will retrieve the value of the "Authorization" header and store it in the authorizationHeader variable.

Manipulating Headers

We can also manipulate headers using the Header().Add() and Header().Del() methods of the http.ResponseWriter object. The Header().Add() method adds a new header with the specified name and value, while the Header().Del() method removes a header with the specified name.

Conclusion

Headers play an important role in REST APIs, as they transmit additional information about requests and responses. In the Go language, handling headers is easy, thanks to the built-in net/http package. You can use the Header.Get(), Header.Set(), and Header.Add() methods to read and set headers in HTTP requests and responses.

I hope this helps, you!!

More such articles:

https://medium.com/techwasti

https://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA

https://www.techwasti.com/

\==========================**=========================

If this article adds any value to you then please clap and comment.

Let’s connect on Stackoverflow, LinkedIn, & Twitter.

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this