Major Refactoring

- Move components to separate packages
- Fix HTTP header for 401 response
- Add documentation
This commit is contained in:
Bendodroid 2023-11-05 20:23:31 +01:00
commit 4b41acfa7b
Signed by: bendodroid
GPG key ID: 3EEE19A0F73D5FFC
5 changed files with 191 additions and 103 deletions

48
util/config.go Normal file
View file

@ -0,0 +1,48 @@
package util
import (
"log"
"os"
"path/filepath"
"gitlab.hamburg.ccc.de/ccchh/spaceapid/config"
)
const (
envBAUsername = "BA_USERNAME"
envBAPassword = "BA_PASSWORD"
envJSONTemplatePath = "JSON_TEMPLATE_PATH"
)
// GetConfiguration gets the spaceapid configuration from the respective environment variables
func GetConfiguration() (c config.Configuration) {
var (
success bool
err error
)
// HTTP BasicAuth username
c.BAUsername, success = os.LookupEnv(envBAUsername)
if !success || c.BAUsername == "" {
log.Fatalln("Could not retrieve env variable", envBAUsername, "or variable is empty")
}
// HTTP BasicAuth password
c.BAPassword, success = os.LookupEnv(envBAPassword)
if !success || c.BAPassword == "" {
log.Fatalln("Could not retrieve", envBAPassword, "env variable or variable is empty")
}
// JSON template path
templatePath, success := os.LookupEnv(envJSONTemplatePath)
if !success || templatePath == "" {
log.Fatalln("Could not retrieve", envJSONTemplatePath, "env variable or variable is empty")
}
// Save as absolute path
c.TemplatePath, err = filepath.Abs(templatePath)
if err != nil {
log.Fatalln("Failed converting", templatePath, "to absolute path:", err)
}
return
}

36
util/util.go Normal file
View file

@ -0,0 +1,36 @@
package util
import (
"bytes"
"encoding/json"
"log"
"os"
"slices"
"gitlab.hamburg.ccc.de/ccchh/spaceapid/types"
)
// ParseTemplate parses the given file and
func ParseTemplate(file string) (resp types.SpaceAPIResponseV14) {
// Read template file
template, err := os.ReadFile(file)
if err != nil {
log.Fatalln("Failed reading file:", err)
}
// Parse JSON
dec := json.NewDecoder(bytes.NewReader(template))
dec.DisallowUnknownFields()
err = dec.Decode(&resp)
if err != nil {
log.Fatalln("Could not parse SpaceAPI response template:", err)
}
// Check if compatible with v14
if !slices.Contains(resp.APICompatibility, "14") {
log.Fatalln("Provided template doesn't specify compatibility with API version 14")
}
return
}