From 82b6721e5fe7e626c6c731e408be9c989caf370c Mon Sep 17 00:00:00 2001 From: xengineering Date: Mon, 25 Mar 2024 20:06:08 +0100 Subject: Define /api handler directly Using a function returning a closure does not really make sense here. --- main.go | 34 +++++++++++++++------------------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/main.go b/main.go index 48a00a5..511b434 100644 --- a/main.go +++ b/main.go @@ -16,7 +16,7 @@ func main() { configPath := parseFlags() c := parseConfig(configPath) http.HandleFunc("/", index(c.Devices)) - http.HandleFunc("/api", api()) + http.HandleFunc("/api", api) http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(static)))) fmt.Printf("Serving at http://%s\n", c.Web.Listen) @@ -51,26 +51,22 @@ func index(devices DevicesConfig) func(http.ResponseWriter, *http.Request) { } } -// api() returns the HTTP handler for the API endpoint. -func api() func(http.ResponseWriter, *http.Request) { - return func(w http.ResponseWriter, r *http.Request) { - - // TODO assert correct HTTP method +func api(w http.ResponseWriter, r *http.Request) { + // TODO assert correct HTTP method - errHost, host := assertSingleParam(r, "host") - errState, state := assertSingleParam(r, "state") - if (errHost != nil) || (errState != nil) { - http.Error(w, - "Provide exactly one host and one state parameter!", 400) - return - } + errHost, host := assertSingleParam(r, "host") + errState, state := assertSingleParam(r, "state") + if (errHost != nil) || (errState != nil) { + http.Error(w, + "Provide exactly one host and one state parameter!", 400) + return + } - err := set(host, state) - if err != nil { - http.Error(w, "Could not set WiFi plug.", 500) - } else { - fmt.Fprint(w, "ok") - } + err := set(host, state) + if err != nil { + http.Error(w, "Could not set WiFi plug.", 500) + } else { + fmt.Fprint(w, "ok") } } -- cgit v1.2.3-70-g09d2