mirror of
https://github.com/containrrr/watchtower.git
synced 2025-12-16 23:20:12 +01:00
feat(api): implement new api handler
This commit is contained in:
parent
72e437f173
commit
47091761a5
17 changed files with 571 additions and 294 deletions
39
pkg/api/prelude/handler_func.go
Normal file
39
pkg/api/prelude/handler_func.go
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
package prelude
|
||||
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type HandlerFunc func(c *Context) Response
|
||||
|
||||
func (hf HandlerFunc) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
|
||||
w.Header().Set("Content-Type", DefaultContentType)
|
||||
context := newContext(w, req)
|
||||
|
||||
reqLog := context.Log.WithFields(log.Fields{
|
||||
"query": req.URL.RawQuery,
|
||||
})
|
||||
reqLog.Trace("Received API Request")
|
||||
|
||||
res := hf(context)
|
||||
|
||||
status := res.Status
|
||||
|
||||
bytes, err := res.Bytes()
|
||||
if err != nil {
|
||||
context.Log.WithError(err).Errorf("Failed to create JSON payload for response")
|
||||
bytes = []byte(internalErrorPayload)
|
||||
status = http.StatusInternalServerError
|
||||
// Reset the content-type in case the handler changed it
|
||||
w.Header().Set("Content-Type", DefaultContentType)
|
||||
}
|
||||
|
||||
reqLog.WithField("status", status).Trace("Handled API Request")
|
||||
|
||||
w.WriteHeader(status)
|
||||
if _, err = w.Write(bytes); err != nil {
|
||||
localLog.Errorf("Failed to write HTTP response: %v", err)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue