programming

04 How to Used Request Header in Golang

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.

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

const X_POWERED_BY = "X-Powered-By"

func RequestHedaerHandler(w http.ResponseWriter, r *http.Request) {
	poweredBy := r.Header.Get(X_POWERED_BY)
	w.Header().Add(X_POWERED_BY, poweredBy)
	fmt.Fprint(w, poweredBy)
}

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.


func TestRequestHedaerHandler(t *testing.T) {
	type args struct {
		name string
	}
	tests := []struct {
		name string
		args args
		want string
	}{
		{
			name: "set powered by",
			args: args{
				name: "santekno",
			},
			want: "santekno",
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			request := httptest.NewRequest(http.MethodGet, "http://localhost/say", nil)
			request.Header.Add(X_POWERED_BY, tt.args.name)
			recorder := httptest.NewRecorder()
			RequestHedaerHandler(recorder, request)

			response := recorder.Result()
			poweredBy := response.Header.Get(X_POWERED_BY)

			if !reflect.DeepEqual(poweredBy, tt.want) {
				t.Errorf("poweredBy = %v, want %v", poweredBy, tt.want)
			}
		})
	}
}
comments powered by Disqus