From e46ab6bc3b6aed18fd11269a578c7b9614fc2e4b Mon Sep 17 00:00:00 2001 From: Shulhan Date: Fri, 27 Nov 2020 18:59:36 +0700 Subject: http: add an example on how to write custom HTTP status code The example show how to use http.ResponseWriter.WriteHeader to write custom HTTP status code instead of relying on errors.E. --- lib/http/example_server_test.go | 69 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 lib/http/example_server_test.go diff --git a/lib/http/example_server_test.go b/lib/http/example_server_test.go new file mode 100644 index 00000000..d5b03933 --- /dev/null +++ b/lib/http/example_server_test.go @@ -0,0 +1,69 @@ +package http + +import ( + "encoding/json" + "fmt" + "log" + "net/http" + "time" +) + +func ExampleServer_customHTTPStatusCode() { + type CustomResponse struct { + Status int `json:"status"` + } + exp := CustomResponse{ + Status: http.StatusBadRequest, + } + + opts := &ServerOptions{ + Address: "127.0.0.1:8123", + } + + testServer, err := NewServer(opts) + if err != nil { + log.Fatal(err) + } + + go func() { + err = testServer.Start() + if err != nil { + log.Println(err) + } + }() + + defer testServer.Stop(5 * time.Second) + + epCustom := &Endpoint{ + Path: "/error/custom", + RequestType: RequestTypeJSON, + ResponseType: ResponseTypeJSON, + Call: func(res http.ResponseWriter, req *http.Request, reqBody []byte) ( + resbody []byte, err error, + ) { + res.WriteHeader(exp.Status) + return json.Marshal(exp) + }, + } + + err = testServer.registerPost(epCustom) + if err != nil { + log.Fatal(err) + } + + // Wait for the server fully started. + time.Sleep(1 * time.Second) + + client := NewClient("http://127.0.0.1:8123", nil, false) + + httpRes, resBody, err := client.PostJSON(nil, epCustom.Path, nil) + if err != nil { + log.Fatal(err) + } + + fmt.Printf("%d\n", httpRes.StatusCode) + fmt.Printf("%s\n", resBody) + // Output: + // 400 + // {"status":400} +} -- cgit v1.3