aboutsummaryrefslogtreecommitdiff
path: root/lib/http/example_server_test.go
diff options
context:
space:
mode:
authorShulhan <m.shulhan@gmail.com>2020-11-27 18:59:36 +0700
committerShulhan <m.shulhan@gmail.com>2020-11-27 18:59:36 +0700
commite46ab6bc3b6aed18fd11269a578c7b9614fc2e4b (patch)
treef4a90b72641033c549ff5d4b55c369dd3d5ed173 /lib/http/example_server_test.go
parent0df82da7a8cd0678ed845f2284b7d3f84ba84687 (diff)
downloadpakakeh.go-e46ab6bc3b6aed18fd11269a578c7b9614fc2e4b.tar.xz
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.
Diffstat (limited to 'lib/http/example_server_test.go')
-rw-r--r--lib/http/example_server_test.go69
1 files changed, 69 insertions, 0 deletions
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}
+}