spud/daemon/daemon.go

72 lines
1.7 KiB
Go
Raw Normal View History

2024-10-02 02:56:25 +00:00
package daemon
import (
"context"
2024-10-02 02:56:25 +00:00
"fmt"
2024-10-03 04:33:08 +00:00
"log/slog"
2024-10-02 02:56:25 +00:00
"net/http"
service "spud/service"
2024-10-03 04:33:08 +00:00
"strconv"
2024-10-02 02:56:25 +00:00
)
type Daemon struct {
Host string
Port int
Services service.ServiceClient
Routes map[string]http.HandlerFunc
2024-10-02 02:56:25 +00:00
}
type HandlerFuncWithContext = func(w http.ResponseWriter, r *http.Request, c context.Context)
2024-10-03 04:33:08 +00:00
type RecordingResponseWriter struct {
responseWriter http.ResponseWriter
StatusCode int
}
func (r *RecordingResponseWriter) WriteHeader(statusCode int) {
r.StatusCode = statusCode
r.responseWriter.WriteHeader(statusCode)
}
func (r RecordingResponseWriter) Write(b []byte) (int, error) {
return r.responseWriter.Write(b)
}
func (r RecordingResponseWriter) Header() http.Header {
return r.responseWriter.Header()
}
func handleFuncWithContext(h HandlerFuncWithContext, c context.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
2024-10-03 04:33:08 +00:00
respWriter := &RecordingResponseWriter{responseWriter: w}
h(respWriter, r, c)
slog.Info("Request", "Method", r.Method, "Path", r.URL.Path, "Status", strconv.Itoa(respWriter.StatusCode))
}
}
func NewDaemon(host string, port int, serviceClient service.ServiceClient) *Daemon {
d := &Daemon{Host: host, Port: port}
if serviceClient == nil {
d.Services = &service.PodmanServiceClient{}
} else {
d.Services = serviceClient
}
return d
2024-10-02 02:56:25 +00:00
}
func (d Daemon) GetListenAddress() string {
return fmt.Sprintf("%s:%d", d.Host, d.Port)
}
func (d Daemon) Start() {
daemonContext := context.WithValue(context.Background(), "client", d.Services)
2024-10-02 02:56:25 +00:00
for route, handler := range GetApiRoutes() {
http.HandleFunc(route, handleFuncWithContext(handler, daemonContext))
2024-10-02 02:56:25 +00:00
}
http.ListenAndServe(d.GetListenAddress(), nil)
}