Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
18 Aug 2023 · 2 min read ·Article 34 / 119
Go

04 How to Used Request Header in Golang

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

Header Introduction

Apart from query parameters on HTTP, we can also use Headers. Headers are additional information that is usually sent from the client to the server or vice versa. In the Header, not only in the HTTP Request but in the HTTP Response we can also add header information. When we use a browser on our computer, usually headers will automatically be displayed by the browser such as browser information, types of content sent and received by the browser and much more.

Understanding Request Headers

In Golang we can capture the request header sent by the client. We can retrieve it in Request.Header. Just like Query Parameters, the contents of the Header are in the form of map[string][]string. But there is a difference with Query Parameters, namely that it is not case sensitive.

Response Headers

Next, if we want to add headers to the response, we can also use ResponseWriter.Header(). We can set the response header in our program as below.

go
1w.Header().Add(X_POWERED_BY, poweredBy)

Implementation

We try to continue implementing it to capture the request header sent by the client. We create the handler as below.

go
1const X_POWERED_BY = "X-Powered-By"
2
3func RequestHedaerHandler(w http.ResponseWriter, r *http.Request) {
4	poweredBy := r.Header.Get(X_POWERED_BY)
5	w.Header().Add(X_POWERED_BY, poweredBy)
6	fmt.Fprint(w, poweredBy)
7}

In the code above we will capture the header with the key X-Powered-By sent by the client then we will print it and carry out testing by creating a unit test as below.

go
 1func TestRequestHedaerHandler(t *testing.T) {
 2	type args struct {
 3		name string
 4	}
 5	tests := []struct {
 6		name string
 7		args args
 8		want string
 9	}{
10		{
11			name: "set powered by",
12			args: args{
13				name: "santekno",
14			},
15			want: "santekno",
16		},
17	}
18	for _, tt := range tests {
19		t.Run(tt.name, func(t *testing.T) {
20			request := httptest.NewRequest(http.MethodGet, "http://localhost/say", nil)
21			request.Header.Add(X_POWERED_BY, tt.args.name)
22			recorder := httptest.NewRecorder()
23			RequestHedaerHandler(recorder, request)
24
25			response := recorder.Result()
26			poweredBy := response.Header.Get(X_POWERED_BY)
27
28			if !reflect.DeepEqual(poweredBy, tt.want) {
29				t.Errorf("poweredBy = %v, want %v", poweredBy, tt.want)
30			}
31		})
32	}
33}

Related Articles

💬 Comments