From 74a8db7d2b1316ebba4fb6075cd7666ec8a547f1 Mon Sep 17 00:00:00 2001 From: Bennett Wetters Date: Sat, 3 Aug 2024 17:55:28 +0200 Subject: [PATCH] refactor: Add Go 1.22 HTTP method matching --- go.mod | 2 +- handlers/util.go | 10 +--------- main.go | 10 +++++----- 3 files changed, 7 insertions(+), 15 deletions(-) diff --git a/go.mod b/go.mod index e3d228e..506613d 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ module git.hamburg.ccc.de/ccchh/spaceapid -go 1.21 +go 1.22 diff --git a/handlers/util.go b/handlers/util.go index 890d983..27c2d9f 100644 --- a/handlers/util.go +++ b/handlers/util.go @@ -10,8 +10,7 @@ import ( "git.hamburg.ccc.de/ccchh/spaceapid/util" ) -// updateEndpointValidator checks BasicAuth credentials, -// checks for correct HTTP method and then returns the request body +// updateEndpointValidator checks BasicAuth credentials and then returns the request body func updateEndpointValidator( authDB config.HTTPBACredentials, validCredentials []config.HTTPBACredentialID, w http.ResponseWriter, r *http.Request, @@ -24,13 +23,6 @@ func updateEndpointValidator( return []byte{}, errors.New(fmt.Sprintf("Unauthorized request from %s Username: %s Password: %s", r.RemoteAddr, username, password)) } - // Check if PUT method - if r.Method != http.MethodPut { - w.Header().Set("Allow", http.MethodPut) - http.Error(w, "", http.StatusMethodNotAllowed) - return []byte{}, errors.New(fmt.Sprintf("Wrong Method: %s from %s at %s", r.Method, r.RemoteAddr, r.RequestURI)) - } - // Read request body body, err := io.ReadAll(r.Body) if err != nil { diff --git a/main.go b/main.go index 4ff0031..4e16106 100644 --- a/main.go +++ b/main.go @@ -51,20 +51,20 @@ func main() { }(&conf.Response) // Register HTTP handlers - http.HandleFunc("/", + http.HandleFunc("GET /{$}", handlers.Root(&conf.Response), ) - http.HandleFunc("/state/open", + http.HandleFunc("PUT /state/open", handlers.StateOpen(conf.Credentials, conf.Dynamic.State.Open.AllowedCredentials, &conf.Response.State), ) - // Register handlers for environmental sensors + // Register handler for environmental sensors for sensorType, envSensorConfigs := range conf.Dynamic.Sensors { for i, envSensorConfig := range envSensorConfigs { - urlPath := util.GetSensorURLPath( + urlPattern := "PUT " + util.GetSensorURLPath( sensorType, envSensorConfig.SensorData.Location, envSensorConfig.SensorData.Name, ) http.HandleFunc( - urlPath, + urlPattern, handlers.EnvironmentSensor( conf.Credentials, envSensorConfig.AllowedCredentials, &conf.Response.Sensors[sensorType][i], ),