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
|
package server
import (
"fmt"
"log"
"net/http"
config "codeberg.org/snonux/gos/internal/config/server"
"codeberg.org/snonux/gos/internal/server/health"
)
const HealthHandlerName = `healthHandler`
type Server struct {
Status health.Status
Conf config.ServerConfig
}
type HandlerFuncWithError func(http.ResponseWriter, *http.Request) error
func New(conf config.ServerConfig) Server {
serv := Server{
Conf: conf,
Status: health.NewStatus(),
}
return serv
}
func (serv Server) Handle(name string, handler HandlerFuncWithError) {
var (
handlerPath = fmt.Sprintf("/%s", name)
handlerName = fmt.Sprintf("%sHandler", name)
)
http.HandleFunc(handlerPath, func(w http.ResponseWriter, r *http.Request) {
log.Println("Someone requested", handlerName)
// The health endpoint doesn't require an API key
if handlerName != HealthHandlerName && r.Header.Get("X-API-KEY") != serv.Conf.APIKey {
http.Error(w, "Invalid API key", http.StatusUnauthorized)
log.Println("Unauthorized access attempt to", handlerName)
return
}
if err := handler(w, r); err != nil {
log.Println(err)
serv.Status.Set(health.Critical, handlerName, err.Error())
return
}
serv.Status.Clear(handlerName)
})
}
|