-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
56 lines (42 loc) · 1.16 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package server_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"github.com/x-ethr/go-http-server/v2"
"github.com/x-ethr/go-http-server/v2/writer"
)
func Example() {
ctx, cancel := context.WithCancel(context.Background())
mux := http.NewServeMux()
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
var response = map[string]interface{}{
"key": "value",
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
})
// Add Response Writer
handler := writer.Handle(mux)
// Start the HTTP server
slog.Info("Starting Server ...", slog.String("local", fmt.Sprintf("http://localhost:%s", "8080")))
api := server.Server(ctx, handler, "8080")
// Issue Cancellation Handler
server.Interrupt(ctx, cancel, api)
// <-- Blocking
if e := api.ListenAndServe(); e != nil && !(errors.Is(e, http.ErrServerClosed)) {
slog.ErrorContext(ctx, "Error During Server's Listen & Serve Call ...", slog.String("error", e.Error()))
os.Exit(100)
}
// --> Exit
{
slog.InfoContext(ctx, "Graceful Shutdown Complete")
// Waiter
<-ctx.Done()
}
}