Refactoring #34

Merged
bendodroid merged 10 commits from :Bendodroid-refactoring into main 2024-05-26 21:06:30 +02:00
2 changed files with 28 additions and 9 deletions
Showing only changes of commit 7218177625 - Show all commits

17
main.go
View file

@ -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],
),
)
}

20
util/util.go Normal file
View file

@ -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)
}