Improve config handling and switch to methods

Amolith created

Change summary

config.go   | 11 +++--------
config.yaml |  5 +++--
delete.go   |  2 +-
edit.go     |  2 +-
go.sum      |  9 +++++++++
login.go    |  2 +-
logout.go   |  2 +-
main.go     | 50 ++++++++++++++++++++++++--------------------------
root.go     |  2 +-
9 files changed, 44 insertions(+), 41 deletions(-)

Detailed changes

config.go 🔗

@@ -1,25 +1,20 @@
 package main
 
 import (
-	"io/ioutil"
 	"log"
 	"os"
 
 	yaml "gopkg.in/yaml.v2"
 )
 
-func parseConfig(configFile *string) {
-	configBytes, err := ioutil.ReadFile(*configFile)
+func (m *model) parseConfig(configFile *string) {
+	configBytes, err := os.ReadFile(*configFile)
 	if err != nil {
 		log.Println("Config file not found, writing default values to config.yaml")
 		writeDefaultConfig()
 		os.Exit(0)
 	}
-	config := make(map[interface{}]interface{})
-	err = yaml.Unmarshal(configBytes, &config)
-	for k, v := range config {
-		log.Printf("%s -> %s\n", k, v)
-	}
+	err = yaml.Unmarshal(configBytes, m)
 }
 
 // TODO

config.yaml 🔗

@@ -1,2 +1,3 @@
-listen: 127.0.0.1:8275
-access_token: mRp3cf9Zxv445DFACsRnaZKW26oehZujBhNneTFLnjXHE7E6Ia
+listen: "127.0.0.1:8275"
+accessToken: "mRp3cf9Zxv445DFACsRnaZKW26oehZujBhNneTFLnjXHE7E6Ia"
+databasePath: "badger_db"

delete.go 🔗

@@ -2,5 +2,5 @@ package main
 
 import "net/http"
 
-func delete(writer http.ResponseWriter, request *http.Request) {
+func (m model) delete(writer http.ResponseWriter, request *http.Request) {
 }

edit.go 🔗

@@ -2,5 +2,5 @@ package main
 
 import "net/http"
 
-func edit(writer http.ResponseWriter, request *http.Request) {
+func (m model) edit(writer http.ResponseWriter, request *http.Request) {
 }

go.sum 🔗

@@ -1,5 +1,6 @@
 cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
 github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
+github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE=
 github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
 github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
 github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko=
@@ -12,6 +13,7 @@ github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8Nz
 github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
 github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE=
 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
 github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
 github.com/dchest/uniuri v0.0.0-20200228104902-7aecb25e1fe5 h1:RAV05c0xOkJ3dZGS0JFybxFKZ2WMLabgx3uXnd7rpGs=
 github.com/dchest/uniuri v0.0.0-20200228104902-7aecb25e1fe5/go.mod h1:GgB8SF9nRG+GqaDtLcwJZsQFhcogVCJ79j4EdT0c2V4=
@@ -19,6 +21,7 @@ github.com/dgraph-io/badger/v3 v3.2103.2 h1:dpyM5eCJAtQCBcMCZcT4UBZchuTJgCywerHH
 github.com/dgraph-io/badger/v3 v3.2103.2/go.mod h1:RHo4/GmYcKKh5Lxu63wLEMHJ70Pac2JqZRYGhlyAo2M=
 github.com/dgraph-io/ristretto v0.1.0 h1:Jv3CGQHp9OjuMBSne1485aDpUkTKEcUqF+jm/LuerPI=
 github.com/dgraph-io/ristretto v0.1.0/go.mod h1:fux0lOrBhrVCJd3lcTHsIJhq1T2rokOu6v9Vcb3Q9ug=
+github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 h1:tdlZCpZ/P9DhczCTSixgIKmwPv6+wP5DGjqLYw5SUiA=
 github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw=
 github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo=
 github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
@@ -45,8 +48,10 @@ github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI
 github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
 github.com/klauspost/compress v1.12.3 h1:G5AfA94pHPysR56qqrkO2pxEexdDzrpFJ6yt/VqWxVU=
 github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg=
+github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
 github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
 github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
+github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
 github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
 github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
 github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
@@ -54,9 +59,11 @@ github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh
 github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
 github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
 github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
 github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
 github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
 github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
+github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI=
 github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
 github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
 github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
@@ -68,6 +75,7 @@ github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An
 github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s=
 github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
 github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
+github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
 github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
 github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0=
 github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
@@ -129,6 +137,7 @@ google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRn
 google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
 google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
 gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
 gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
 gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=

login.go 🔗

@@ -2,5 +2,5 @@ package main
 
 import "net/http"
 
-func login(writer http.ResponseWriter, request *http.Request) {
+func (m model) login(writer http.ResponseWriter, request *http.Request) {
 }

logout.go 🔗

@@ -2,5 +2,5 @@ package main
 
 import "net/http"
 
-func logout(writer http.ResponseWriter, request *http.Request) {
+func (m model) logout(writer http.ResponseWriter, request *http.Request) {
 }

main.go 🔗

@@ -12,52 +12,50 @@ import (
 //go:embed templates
 var templates embed.FS
 
-var db *badger.DB
+var flagConfig *string = flag.StringP("config", "c", "config.yaml", "Path to config file")
 
-var (
-	flagListen      *string = flag.StringP("listen", "l", "127.0.0.1:2857", "Host and port umu will listen on")
-	flagConfig      *string = flag.StringP("config", "c", "config.yaml", "Path to config file")
-	flagAccessToken *string = flag.StringP("accesstoken", "a", "CHANGEME", "Access token, best defined in config.yaml")
-	flagDatabase    *string = flag.StringP("database", "d", "badger_db", "Path to badger database file")
-)
-
-type config struct {
-	listen      string
-	config      string
-	accessToken string
+type model struct {
+	Listen       string `yaml:"listen"`
+	AccessToken  string `yaml:"accessToken"`
+	DatabasePath string `yaml:"databasePath"`
+	database     *badger.DB
 }
 
-func init() {
+func (m *model) init() {
 	flag.Parse()
 	log.Println("Reading config at", *flagConfig)
-	parseConfig(&*flagConfig)
-	log.Println("Listening on", *flagListen)
-	if *flagAccessToken == "CHANGEME" {
+	m.parseConfig(&*flagConfig)
+	log.Println("Listening on", m.Listen)
+	if m.AccessToken == "CHANGEME" {
 		log.Fatalln("Access token *must* be defined, either by flag or config file.")
 	}
-	log.Println("Reading database at", *flagDatabase+"/")
+	log.Println("Reading database at", m.DatabasePath+"/")
 }
 
 func main() {
-	db, err := badger.Open(badger.DefaultOptions(*flagDatabase))
+	m := model{}
+	m.init()
+
+	db, err := badger.Open(badger.DefaultOptions(m.DatabasePath))
+	m.database = db
 	if err != nil {
 		log.Fatal(err)
 	}
-	defer db.Close()
+	defer m.database.Close()
 
 	mux := http.NewServeMux()
 
 	httpServer := &http.Server{
-		Addr:    *flagListen,
+		Addr:    m.Listen,
 		Handler: mux,
 	}
 
-	mux.HandleFunc("/", root)
-	mux.HandleFunc("/login", login)
-	mux.HandleFunc("/logout", logout)
-	mux.HandleFunc("/create", create)
-	mux.HandleFunc("/delete", delete)
-	mux.HandleFunc("/edit", edit)
+	mux.HandleFunc("/", m.root)
+	mux.HandleFunc("/login", m.login)
+	mux.HandleFunc("/logout", m.logout)
+	mux.HandleFunc("/create", m.create)
+	mux.HandleFunc("/delete", m.delete)
+	mux.HandleFunc("/edit", m.edit)
 
 	if err = httpServer.ListenAndServe(); err == http.ErrServerClosed {
 		log.Println("Web server closed")

root.go 🔗

@@ -6,7 +6,7 @@ import (
 	"net/http"
 )
 
-func root(writer http.ResponseWriter, request *http.Request) {
+func (m model) root(writer http.ResponseWriter, request *http.Request) {
 	home, err := templates.ReadFile("templates/home_unauthenticated.html")
 	if err != nil {
 		log.Fatalln(err)