diff options
| author | Shulhan <m.shulhan@gmail.com> | 2020-11-27 19:49:50 +0700 |
|---|---|---|
| committer | Shulhan <m.shulhan@gmail.com> | 2020-11-27 19:49:50 +0700 |
| commit | caa050939faabc96a7c5a7ca53d1f844d64d010d (patch) | |
| tree | 22773a02d5f6c33cd107b6bd455173946d235b62 /lib/http/endpoint_example_test.go | |
| parent | e46ab6bc3b6aed18fd11269a578c7b9614fc2e4b (diff) | |
| download | pakakeh.go-caa050939faabc96a7c5a7ca53d1f844d64d010d.tar.xz | |
http: allow Endpoint to register custom error handler
The new field ErrorHandler on Endpoint allow the implementor to define
their own function to handler error from Endpoint.Call.
If the ErrorHandler is nil it will default to DefaultErrorHandler.
Diffstat (limited to 'lib/http/endpoint_example_test.go')
| -rw-r--r-- | lib/http/endpoint_example_test.go | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/lib/http/endpoint_example_test.go b/lib/http/endpoint_example_test.go new file mode 100644 index 00000000..b605a931 --- /dev/null +++ b/lib/http/endpoint_example_test.go @@ -0,0 +1,62 @@ +package http + +import ( + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +func ExampleEndpoint_errorHandler() { + serverOpts := &ServerOptions{ + Address: "127.0.0.1:8123", + } + server, _ := NewServer(serverOpts) + + endpointError := &Endpoint{ + Method: RequestMethodGet, + Path: "/", + RequestType: RequestTypeQuery, + ResponseType: ResponseTypePlain, + Call: func(res http.ResponseWriter, req *http.Request, reqBody []byte) ([]byte, error) { + return nil, fmt.Errorf(req.Form.Get("error")) + }, + ErrorHandler: func(res http.ResponseWriter, req *http.Request, err error) { + res.Header().Set(HeaderContentType, ContentTypePlain) + + codeMsg := strings.Split(err.Error(), ":") + if len(codeMsg) != 2 { + res.WriteHeader(http.StatusInternalServerError) + res.Write([]byte(err.Error())) + } else { + code, _ := strconv.Atoi(codeMsg[0]) + res.WriteHeader(code) + res.Write([]byte(codeMsg[1])) + } + }, + } + _ = server.RegisterEndpoint(endpointError) + + go func() { + _ = server.Start() + }() + defer server.Stop(1 * time.Second) + time.Sleep(1 * time.Second) + + client := NewClient("http://"+serverOpts.Address, nil, false) + + params := url.Values{} + params.Set("error", "400:error with status code") + httpres, resbody, _ := client.Get(nil, "/", params) + fmt.Printf("%d: %s\n", httpres.StatusCode, resbody) + + params.Set("error", "error without status code") + httpres, resbody, _ = client.Get(nil, "/", params) + fmt.Printf("%d: %s\n", httpres.StatusCode, resbody) + + // Output: + // 400: error with status code + // 500: error without status code +} |
