From 031ed467802392b4a43f6c88ef66e15592016b9c Mon Sep 17 00:00:00 2001 From: Christian Pointner Date: Sat, 24 Sep 2016 19:30:20 +0200 Subject: implemented state web api endpoint diff --git a/src/rhctl/web.go b/src/rhctl/web.go index b3b35d7..3c29c56 100644 --- a/src/rhctl/web.go +++ b/src/rhctl/web.go @@ -23,6 +23,7 @@ package main import ( "encoding/json" + "fmt" "net/http" "time" ) @@ -47,8 +48,32 @@ func webSendResponse(w http.ResponseWriter, status int, respdata interface{}) { encoder.Encode(respdata) } -func webPingHandler(ctrl *SwitchControl, w http.ResponseWriter, r *http.Request) { - webSendResponse(w, http.StatusOK, "pong") +type webError struct { + ResponseCode int `json:"RESPONSE_CODE"` + ErrorString string `json:"ERROR_STRING"` +} + +func webSendErrorResponse(w http.ResponseWriter, status int, error string) { + webSendResponse(w, http.StatusOK, webError{ResponseCode: status, ErrorString: error}) +} + +func webGetStateHandler(ctrl *SwitchControl, w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" { + webSendErrorResponse(w, http.StatusMethodNotAllowed, "only GET method is allowed") + return + } + + resp := make(chan interface{}) + ctrl.Commands <- &Command{Type: CmdState, Response: resp} + result := <-resp + switch result.(type) { + case State: + webSendResponse(w, http.StatusOK, result.(State)) + case error: + webSendErrorResponse(w, http.StatusInternalServerError, result.(error).Error()) + default: + webSendErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("invalid response of type %T: %+v", result, result)) + } } func (web *WebInterface) Run() { @@ -65,7 +90,7 @@ func WebInit(conf *Config, ctrl *SwitchControl) (web *WebInterface) { rhdl.Printf("Web: will serving static files from '%s'", conf.Clients.Web.StaticDir) http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(conf.Clients.Web.StaticDir)))) } - http.Handle("/ping", webHandler{ctrl, webPingHandler}) + http.Handle("/api/state", webHandler{ctrl, webGetStateHandler}) // TODO: add other handler web.server = &http.Server{Addr: conf.Clients.Web.Address, ReadTimeout: 2 * time.Hour, WriteTimeout: 2 * time.Hour} -- cgit v0.10.2