spud/daemon/api.go

59 lines
1.4 KiB
Go

package daemon
import (
"context"
"encoding/json"
"net/http"
service "spud/service"
service_definition "spud/service_definition"
)
func GetApiRoutes() map[string]HandlerFuncWithContext {
return map[string]HandlerFuncWithContext{
"/service/": ServiceList,
"/service/{serviceName}/": ServiceDetails,
}
}
type ServiceListPayload struct {
Definition service_definition.ServiceDefinition `json:"definition"`
}
func handleServiceListPost(w http.ResponseWriter, r *http.Request, c context.Context) {
client := c.Value("client").(service.ServiceClient)
var p ServiceListPayload
json.NewDecoder(r.Body).Decode(&p)
client.Create(p.Definition)
w.WriteHeader(201)
json.NewEncoder(w).Encode(p.Definition)
}
func handleServiceDetailDelete(w http.ResponseWriter, r *http.Request, c context.Context) {
client := c.Value("client").(service.ServiceClient)
serviceName := r.PathValue("serviceName")
client.Stop(serviceName)
w.WriteHeader(204)
}
func handleNotImplemented(w http.ResponseWriter) {
w.WriteHeader(501)
}
func ServiceList(w http.ResponseWriter, r *http.Request, c context.Context) {
switch r.Method {
case http.MethodPost:
handleServiceListPost(w, r, c)
default:
handleNotImplemented(w)
}
}
func ServiceDetails(w http.ResponseWriter, r *http.Request, c context.Context) {
switch r.Method {
case http.MethodDelete:
handleServiceDetailDelete(w, r, c)
default:
handleNotImplemented(w)
}
}