impl config State and config Interval

master
Bel LaPointe 2022-01-09 21:23:27 -05:00
parent 18215b42c0
commit bf3c382877
6 changed files with 101 additions and 4 deletions

4
config.json Normal file
View File

@ -0,0 +1,4 @@
{
"Interval": "1m",
"States": ["NC"]
}

View File

@ -1,7 +1,35 @@
package config package config
import "errors" import (
"encoding/json"
"io/ioutil"
"os"
)
type Config struct {
Interval Duration
States []State
}
var live Config
func Refresh() error { func Refresh() error {
return errors.New("not impl") configPath, ok := os.LookupEnv("CONFIG")
if !ok {
configPath = "./config.json"
}
b, err := ioutil.ReadFile(configPath)
if err != nil {
return err
}
var c Config
if err := json.Unmarshal(b, &c); err != nil {
return err
}
live = c
return nil
}
func Get() Config {
return live
} }

25
config/duration.go Normal file
View File

@ -0,0 +1,25 @@
package config
import (
"encoding/json"
"time"
)
type Duration time.Duration
func (d Duration) Get() time.Duration {
return time.Duration(d)
}
func (d *Duration) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
d2, err := time.ParseDuration(s)
if err != nil {
return err
}
*d = Duration(d2)
return nil
}

27
config/state.go Normal file
View File

@ -0,0 +1,27 @@
package config
import (
"encoding/json"
"errors"
)
type State string
var States = map[int]State{
27006: "NC",
84058: "UT",
}
func (state *State) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
for k := range States {
if string(States[k]) == s {
*state = States[k]
return nil
}
}
return errors.New("unknown state " + s)
}

2
go.mod
View File

@ -1,3 +1,3 @@
module truckstop module local/truckstop
go 1.17 go 1.17

15
main.go
View File

@ -2,7 +2,9 @@ package main
import ( import (
"errors" "errors"
"fmt"
"local/truckstop/config" "local/truckstop/config"
"time"
) )
func main() { func main() {
@ -15,5 +17,16 @@ func _main() error {
if err := config.Refresh(); err != nil { if err := config.Refresh(); err != nil {
return err return err
} }
return errors.New("not impl") for {
if err := once(); err != nil {
return err
}
time.Sleep(config.Get().Interval.Get())
}
return nil
}
func once() error {
states := config.Get().States
return errors.New("not impl" + fmt.Sprint(states))
} }