48 lines
1.1 KiB
Go
48 lines
1.1 KiB
Go
package daemon
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net/http"
|
|
service "spud/service"
|
|
)
|
|
|
|
type Daemon struct {
|
|
Host string
|
|
Port int
|
|
Services service.ServiceClient
|
|
Routes map[string]http.HandlerFunc
|
|
}
|
|
|
|
type HandlerFuncWithContext = func(w http.ResponseWriter, r *http.Request, c context.Context)
|
|
|
|
func handleFuncWithContext(h HandlerFuncWithContext, c context.Context) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
h(w, r, c)
|
|
}
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
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)
|
|
for route, handler := range GetApiRoutes() {
|
|
http.HandleFunc(route, handleFuncWithContext(handler, daemonContext))
|
|
}
|
|
|
|
http.ListenAndServe(d.GetListenAddress(), nil)
|
|
}
|