arcast/pkg/config/config.go

119 lines
2.7 KiB
Go

package config
import (
"context"
"encoding/json"
"os"
"path/filepath"
"forge.cadoles.com/arcad/arcast/pkg/server"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/logger"
)
type Config struct {
InstanceID string `json:"instanceId"`
HTTP HTTPConfig `json:"http"`
HTTPS HTTPSConfig `json:"https"`
Apps AppsConfig `json:"apps"`
AllowedOrigins []string `json:"allowedOrigins"`
}
type HTTPConfig struct {
Address string `json:"address"`
CustomDir string `json:"customDir"`
}
type HTTPSConfig struct {
Address string `json:"address"`
Cert []byte `json:"cert"`
Key []byte `json:"key"`
SelfSigned SelfSignedCertConfig `json:"selfSigned"`
}
type SelfSignedCertConfig struct {
Enabled bool `json:"enabled"`
NetworkFingerprint string `json:"networkFingerprint"`
}
type AppsConfig struct {
Enabled bool `json:"enabled"`
DefaultApp string `json:"defaultApp"`
}
type TransformFunc func(ctx context.Context, filename string, conf *Config) error
func DefaultConfigFile(ctx context.Context) string {
configDir, err := os.UserConfigDir()
if err != nil {
logger.Error(ctx, "could not get user config dir", logger.CapturedE(errors.WithStack(err)))
configDir = ""
}
if configDir != "" {
configDir = filepath.Join(configDir, "arcast-player")
}
return filepath.Join(configDir, "config.json")
}
func LoadOrCreate(ctx context.Context, filename string, conf *Config, funcs ...TransformFunc) error {
data, err := os.ReadFile(filename)
if err != nil && !os.IsNotExist(err) {
return errors.WithStack(err)
}
if data != nil {
if err := json.Unmarshal(data, conf); err != nil {
logger.Error(ctx, "could not parse configuration file", logger.CapturedE(errors.WithStack(err)))
}
}
for _, fn := range funcs {
if err := fn(ctx, filename, conf); err != nil {
return errors.WithStack(err)
}
}
data, err = json.MarshalIndent(conf, "", " ")
if err != nil {
return errors.WithStack(err)
}
dirname := filepath.Dir(filename)
if _, err := os.Stat(dirname); os.IsNotExist(err) {
if err := os.MkdirAll(dirname, 0777); err != nil {
return errors.WithStack(err)
}
}
if err := os.WriteFile(filename, data, 0640); err != nil {
return errors.WithStack(err)
}
return nil
}
func DefaultConfig() *Config {
return &Config{
InstanceID: server.NewRandomInstanceID(),
AllowedOrigins: []string{},
HTTP: HTTPConfig{
Address: ":45555",
CustomDir: "",
},
HTTPS: HTTPSConfig{
Address: ":45556",
SelfSigned: SelfSignedCertConfig{
Enabled: true,
NetworkFingerprint: "",
},
},
Apps: AppsConfig{
Enabled: true,
DefaultApp: "main",
},
}
}