diff options
-rw-r--r-- | src/rhctl/web.go | 31 |
1 files changed, 28 insertions, 3 deletions
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} |