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

06 How to Used Response Code in Golang

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

Introduction to Response Codes

Something we also need to know about HTTP is the response code. This is a representation of the response code, where from this code we can see whether a request we sent from the client was successfully processed by the server or failed to be processed by the server. So there are lots of response codes that we can use when creating a website. You can immediately look in more depth at several HTTP Status Codes here https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

There are 5 groups of HTTP Response Status Codes which are explained in the link above, namely:

  1. Informational response (100 - 199): usually this is used to inform the response of the status. This is rarely used.
  2. Successful responses (200 - 299) are used for successful responses
  3. Redirects (300 - 399): used to redirect to a specific URL
  4. Client errors (400 - 499): used to inform that there are several incorrect params or requests
  5. Server errors (500 - 599): used to inform that there is a problem with the server process

By default, if we don’t set a response code, it will output code 200, which means success. If we want to change it, we can use the ResponseWriter.WriteHeader(int) function to provide response code information. All status code data has also been provided by Golang, so if we want to use it we just need to call the variables provided in Golang here https://github.com/golang/go/blob/master/src/net/http/status.go .

Implementation

Now we will try to change the response code returned from our system like the code below.

go
 1func ResponseCodeHandler(w http.ResponseWriter, r *http.Request) {
 2	name := r.URL.Query().Get("name")
 3	if name == "" {
 4		w.WriteHeader(http.StatusBadRequest)
 5		fmt.Fprint(w, "name is empty")
 6	} else {
 7		w.WriteHeader(http.StatusOK)
 8		fmt.Fprintf(w, "Hello %s", name)
 9	}
10}

Next, we will test the function that we have created above by adding a unit test so that we know whether the logic process we created is correct or not.

go
 1func TestResponseCodeHandler(t *testing.T) {
 2	type args struct {
 3		name string
 4	}
 5	tests := []struct {
 6		name     string
 7		args     args
 8		wantResp string
 9		wantCode int
10	}{
11		{
12			name: "sent param name with value",
13			args: args{
14				name: "ihsan",
15			},
16			wantResp: "Hello ihsan",
17			wantCode: http.StatusOK,
18		},
19		{
20			name: "does't sent param name",
21			args: args{
22				name: "",
23			},
24			wantResp: "name is empty",
25			wantCode: http.StatusBadRequest,
26		},
27	}
28	for _, tt := range tests {
29		t.Run(tt.name, func(t *testing.T) {
30			request := httptest.NewRequest(http.MethodGet, fmt.Sprintf("http://localhost/say?name=%s", tt.args.name), nil)
31			recorder := httptest.NewRecorder()
32			ResponseCodeHandler(recorder, request)
33
34			response := recorder.Result()
35			body, _ := io.ReadAll(response.Body)
36			bodyString := string(body)
37			code := response.StatusCode
38
39			if !reflect.DeepEqual(bodyString, tt.wantResp) {
40				t.Errorf("response = %v, want %v", bodyString, tt.wantResp)
41			}
42
43			if !reflect.DeepEqual(code, tt.wantCode) {
44				t.Errorf("code = %v, want %v", code, tt.wantCode)
45			}
46		})
47	}
48}

Related Articles

💬 Comments