From 7218177625e722e603fbd69b0a3eb0c1a5cefc25 Mon Sep 17 00:00:00 2001 From: Bennett Wetters Date: Tue, 13 Feb 2024 19:42:37 +0100 Subject: [PATCH] Refactor environment sensor URL path generation --- main.go | 17 ++++++++--------- util/util.go | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 9 deletions(-) create mode 100644 util/util.go diff --git a/main.go b/main.go index 3983cbd..8e4b013 100644 --- a/main.go +++ b/main.go @@ -2,18 +2,17 @@ package main import ( "flag" - "fmt" "log" "net/http" "os" "os/signal" - "strings" "syscall" "git.hamburg.ccc.de/ccchh/spaceapid/config" "git.hamburg.ccc.de/ccchh/spaceapid/handlers" "git.hamburg.ccc.de/ccchh/spaceapid/persistence" "git.hamburg.ccc.de/ccchh/spaceapid/types" + "git.hamburg.ccc.de/ccchh/spaceapid/util" ) var ( @@ -59,15 +58,15 @@ func main() { handlers.StateOpen(conf.Credentials, conf.Dynamic.State.Open.AllowedCredentials, &conf.Response.State), ) // Register handlers for Environmental Sensors - for key, envSensorConfigs := range conf.Dynamic.Sensors { + for sensorType, envSensorConfigs := range conf.Dynamic.Sensors { for i, envSensorConfig := range envSensorConfigs { - pattern := fmt.Sprintf("/sensors/%s/%s", key, envSensorConfig.SensorData.Location) - if envSensorConfig.SensorData.Name != "" { - pattern += "/" + envSensorConfig.SensorData.Name - } - http.HandleFunc(strings.ToLower(pattern), + urlPath := util.GetSensorURLPath( + sensorType, envSensorConfig.SensorData.Location, envSensorConfig.SensorData.Name, + ) + http.HandleFunc( + urlPath, handlers.EnvironmentSensor( - conf.Credentials, envSensorConfig.AllowedCredentials, &conf.Response.Sensors[key][i], + conf.Credentials, envSensorConfig.AllowedCredentials, &conf.Response.Sensors[sensorType][i], ), ) } diff --git a/util/util.go b/util/util.go new file mode 100644 index 0000000..421f72c --- /dev/null +++ b/util/util.go @@ -0,0 +1,20 @@ +package util + +import ( + "fmt" + "strings" +) + +// GetSensorURLPath generates the URL path for the given sensor details. +// location and name may be optional depending on sensorType, see the schema definition for details. +// The path is always all-lowercase. +func GetSensorURLPath(sensorType, location, name string) string { + path := fmt.Sprintf("/sensors/%s", sensorType) + if location != "" { + path += "/" + location + } + if name != "" { + path += "/" + name + } + return strings.ToLower(path) +}