diff options
| author | Shulhan <ms@kilabit.info> | 2024-03-08 02:19:18 +0700 |
|---|---|---|
| committer | Shulhan <ms@kilabit.info> | 2024-03-09 01:10:24 +0700 |
| commit | 4e35c509a41cecb207bf6f52e7c9a529fa9f71fb (patch) | |
| tree | 4fda47608b7a226afed77344003ab8e8f1a4788d /lib/http/server_example_test.go | |
| parent | d309b58f63cfc382e0003cff85ab057fd06d3d23 (diff) | |
| download | pakakeh.go-4e35c509a41cecb207bf6f52e7c9a529fa9f71fb.tar.xz | |
lib/http: rename files for consistency
If the type is in CamelCase the file should be using snake_case.
Diffstat (limited to 'lib/http/server_example_test.go')
| -rw-r--r-- | lib/http/server_example_test.go | 86 |
1 files changed, 86 insertions, 0 deletions
diff --git a/lib/http/server_example_test.go b/lib/http/server_example_test.go new file mode 100644 index 00000000..74a60f2a --- /dev/null +++ b/lib/http/server_example_test.go @@ -0,0 +1,86 @@ +// Copyright 2020, Shulhan <ms@kilabit.info>. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package http + +import ( + "encoding/json" + "fmt" + "log" + "net/http" + "time" +) + +func ExampleServer_customHTTPStatusCode() { + type CustomResponse struct { + Status int `json:"status"` + } + + var ( + exp = CustomResponse{ + Status: http.StatusBadRequest, + } + + opts = &ServerOptions{ + Address: "127.0.0.1:8123", + } + + srv *Server + err error + ) + + srv, err = NewServer(opts) + if err != nil { + log.Fatal(err) + } + + go func() { + err = srv.Start() + if err != nil { + log.Println(err) + } + }() + + defer func() { + _ = srv.Stop(5 * time.Second) + }() + + epCustom := &Endpoint{ + Path: "/error/custom", + RequestType: RequestTypeJSON, + ResponseType: ResponseTypeJSON, + Call: func(epr *EndpointRequest) ( + resbody []byte, err error, + ) { + epr.HTTPWriter.WriteHeader(exp.Status) + return json.Marshal(exp) + }, + } + + err = srv.registerPost(epCustom) + if err != nil { + log.Println(err) + return + } + + // Wait for the server fully started. + time.Sleep(1 * time.Second) + + clientOpts := &ClientOptions{ + ServerURL: `http://127.0.0.1:8123`, + } + client := NewClient(clientOpts) + + httpRes, resBody, err := client.PostJSON(epCustom.Path, nil, nil) //nolint: bodyclose + if err != nil { + log.Println(err) + return + } + + fmt.Printf("%d\n", httpRes.StatusCode) + fmt.Printf("%s\n", resBody) + // Output: + // 400 + // {"status":400} +} |
