diff options
| author | Paul Buetow <paul@buetow.org> | 2024-05-11 12:59:12 +0300 |
|---|---|---|
| committer | Paul Buetow <paul@buetow.org> | 2024-05-11 12:59:12 +0300 |
| commit | 2337c4c11eda933f9c91b46defca63dc5557eb19 (patch) | |
| tree | d6c607013e4fba6fce8dcbbd4b9e53c9e15341be /internal/server | |
| parent | 653057ac9d2ba6783233bc0f59a6a7ca111ad11c (diff) | |
move server struct to server.go
Diffstat (limited to 'internal/server')
| -rw-r--r-- | internal/server/server.go | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/internal/server/server.go b/internal/server/server.go new file mode 100644 index 0000000..6013c1a --- /dev/null +++ b/internal/server/server.go @@ -0,0 +1,50 @@ +package server + +import ( + "fmt" + "log" + "net/http" + + "codeberg.org/snonux/gos/internal/config" + "codeberg.org/snonux/gos/internal/server/health" +) + +const HealthHandlerName = `healthHandler` + +type Server struct { + Status health.Status + Conf config.Config +} + +type HandlerFuncWithError func(http.ResponseWriter, *http.Request) error + +func New(conf config.Config) Server { + return Server{ + Conf: conf, + Status: health.NewStatus(), + } +} + +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 { + serv.Status.Set(health.Critical, handlerName, err.Error()) + return + } + serv.Status.Clear(handlerName) + }) +} |
