Skip to content

Commit

Permalink
support config update over restapi
Browse files Browse the repository at this point in the history
  • Loading branch information
hexian000 committed Dec 11, 2023
1 parent 2f753fa commit 31861f0
Show file tree
Hide file tree
Showing 3 changed files with 193 additions and 152 deletions.
24 changes: 2 additions & 22 deletions v2/cmd/tlswrapper/main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package main

import (
"encoding/json"
"flag"
"fmt"
"os"
Expand All @@ -28,28 +27,9 @@ func parseFlags() string {
return flagConfig
}

func readConfig(path string) (*tlswrapper.Config, error) {
b, err := os.ReadFile(path)
if err != nil {
return nil, err
}
cfg := tlswrapper.DefaultConfig
if err := json.Unmarshal(b, &cfg); err != nil {
return nil, err
}
if err := cfg.Validate(); err != nil {
return nil, err
}
slog.Default().SetLevel(cfg.LogLevel)
if err := slog.Default().SetOutputConfig(cfg.Log, "tlswrapper"); err != nil {
return nil, err
}
return &cfg, nil
}

func main() {
path := parseFlags()
cfg, err := readConfig(path)
cfg, err := tlswrapper.ReadConfig(path)
if err != nil {
slog.Fatal("read config: ", err)
os.Exit(1)
Expand Down Expand Up @@ -78,7 +58,7 @@ func main() {
}
// reload
_, _ = sd.Notify(sd.Reloading)
cfg, err := readConfig(path)
cfg, err := tlswrapper.ReadConfig(path)
if err != nil {
slog.Error("read config: ", err)
continue
Expand Down
24 changes: 24 additions & 0 deletions v2/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package tlswrapper
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"log"
"math"
Expand Down Expand Up @@ -97,6 +98,29 @@ var DefaultConfig = Config{
LogLevel: slog.LevelNotice,
}

func parseConfig(b []byte) (*Config, error) {
cfg := DefaultConfig
if err := json.Unmarshal(b, &cfg); err != nil {
return nil, err
}
if err := cfg.Validate(); err != nil {
return nil, err
}
slog.Default().SetLevel(cfg.LogLevel)
if err := slog.Default().SetOutputConfig(cfg.Log, "tlswrapper"); err != nil {
return nil, err
}
return &cfg, nil
}

func ReadConfig(path string) (*Config, error) {
b, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return parseConfig(b)
}

func rangeCheckInt(key string, value int, min int, max int) error {
if !(min <= value && value <= max) {
return fmt.Errorf("%s is out of range (%d - %d)", key, min, max)
Expand Down
Loading

0 comments on commit 31861f0

Please sign in to comment.