add auth for future https srever and cfgHandler to load configuration

This commit is contained in:
Adrian Zuercher
2025-04-21 09:55:11 +02:00
parent 2273a6140f
commit b777716aa7
2 changed files with 78 additions and 0 deletions

15
auth/auth.go Normal file
View File

@@ -0,0 +1,15 @@
package auth
import (
"errors"
"github.com/gin-gonic/gin"
)
func GetIDFromAuth(c *gin.Context) (string, error) {
auth := c.GetHeader("Authorization")
if len(auth) > 7 && auth[:7] == "Bearer " {
return auth[7:], nil
}
return "", errors.New("authorization token missing")
}

63
cfg/cfg.go Normal file
View File

@@ -0,0 +1,63 @@
package cfg
import (
"fmt"
"os"
"path"
"gopkg.in/yaml.v3"
)
type Cfg struct {
Name string
Dir string
}
// Initializes new config handler
// dir is config directory from working dir on
// name is filename, file extention is automatically added '.cfg'
// file is in yaml format
// if file exists it will read its content in to the driver
func NewCfgHandler(dir, name string) *Cfg {
return &Cfg{
Dir: dir,
Name: name,
}
}
func (c *Cfg) SaveCfg(data any) error {
if _, err := os.Stat(c.Dir); err != nil {
if err := os.MkdirAll(c.Dir, 0666); err != nil {
return err
}
}
f, err := os.Create(path.Join(c.Dir, c.Name) + ".cfg")
if err != nil {
return err
}
defer f.Close()
encoder := yaml.NewEncoder(f)
encoder.SetIndent(2)
if err := encoder.Encode(data); err != nil {
return err
}
encoder.Close()
return nil
}
func (c *Cfg) LoadCfg(data any) error {
p := path.Join(c.Dir, c.Name) + ".cfg"
if _, err := os.Stat(p); err != nil {
return fmt.Errorf("no configuration file: '%s' found", p)
}
b, err := os.ReadFile(p)
if err != nil {
return err
}
return yaml.Unmarshal(b, data)
}