Files
hamlab/internal/config/config.go
T

101 lines
2.3 KiB
Go

// Package config loads and saves hamlab's JSON config file.
package config
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"time"
)
// Token is an API token another Ham Lab (a hub) uses to manage this host. Only the
// SHA-256 of the token is kept.
type Token struct {
Name string `json:"name"`
Hash string `json:"hash"`
Created time.Time `json:"created"`
}
// Node is a remote Ham Lab this host (as hub) manages. The token is the one that
// node issued to us; the fingerprint pins its self-signed certificate.
type Node struct {
Name string `json:"name"`
URL string `json:"url"`
Fingerprint string `json:"fingerprint,omitempty"`
Token string `json:"token"`
Added time.Time `json:"added"`
}
type Config struct {
Listen string `json:"listen"`
PasswordHash string `json:"password_hash"`
TLS string `json:"tls,omitempty"` // "auto" → self-signed cert in the data dir; "" → plain HTTP
Tokens []Token `json:"tokens,omitempty"`
Nodes []Node `json:"nodes,omitempty"`
path string
mu sync.Mutex
}
func Default(path string) *Config {
return &Config{Listen: "127.0.0.1:8100", path: path}
}
// Load reads the config at path. A missing file yields the defaults.
func Load(path string) (*Config, error) {
c := Default(path)
b, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return c, nil
}
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, c); err != nil {
return nil, fmt.Errorf("parse %s: %w", path, err)
}
return c, nil
}
func (c *Config) Path() string { return c.path }
func (c *Config) DataDir() string { return filepath.Dir(c.path) }
func (c *Config) Save() error {
c.mu.Lock()
defer c.mu.Unlock()
return c.save()
}
func (c *Config) save() error {
if err := os.MkdirAll(c.DataDir(), 0o700); err != nil {
return err
}
b, err := json.MarshalIndent(c, "", " ")
if err != nil {
return err
}
tmp := c.path + ".tmp"
if err := os.WriteFile(tmp, append(b, '\n'), 0o600); err != nil {
return err
}
return os.Rename(tmp, c.path)
}
// Update applies fn under the lock and saves.
func (c *Config) Update(fn func(*Config)) error {
c.mu.Lock()
defer c.mu.Unlock()
fn(c)
return c.save()
}
// View reads under the lock.
func (c *Config) View(fn func(*Config)) {
c.mu.Lock()
defer c.mu.Unlock()
fn(c)
}