-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutes.go
73 lines (54 loc) · 1.54 KB
/
routes.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"encoding/json"
"net/http"
"os"
"log/slog"
"go.opentelemetry.io/otel"
)
type Route struct {
logger *slog.Logger
}
type HostnameResponse struct {
Hostname string `json:"hostname"`
}
func (rt *Route) loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
newCtx, span := otel.Tracer("routes").Start(r.Context(), "Log")
defer span.End()
next.ServeHTTP(w, r.WithContext(newCtx))
rt.logger.InfoContext(r.Context(), r.Method+" request", slog.String("path", r.URL.Path))
})
}
func (rt *Route) getHostname(w http.ResponseWriter, r *http.Request) {
_, span := otel.Tracer("routes").Start(r.Context(), "Host")
defer span.End()
hostname, err := os.Hostname()
if err != nil {
rt.logger.ErrorContext(r.Context(), err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(HostnameResponse{
Hostname: hostname,
})
if err != nil {
rt.logger.ErrorContext(r.Context(), err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func (rt *Route) healthcheck(w http.ResponseWriter, r *http.Request) {
_, span := otel.Tracer("routes").Start(r.Context(), "Healthcheck")
defer span.End()
w.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(w).Encode(map[string]string{
"status": "up",
})
if err != nil {
rt.logger.ErrorContext(r.Context(), err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
}