Config file logic

This commit is contained in:
Alex 2020-02-09 15:01:20 +01:00
parent d12afb8a15
commit 8f5ab6cab3
2 changed files with 75 additions and 11 deletions

1
.gitignore vendored
View file

@ -1 +1,2 @@
guichet guichet
config.json

85
main.go
View file

@ -2,29 +2,92 @@ package main
import ( import (
"os" "os"
"flag"
"fmt"
"log" "log"
"net/http" "net/http"
"fmt" "io/ioutil"
"encoding/json"
"encoding/base64"
"crypto/rand"
"github.com/gorilla/sessions" "github.com/gorilla/sessions"
) )
var store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY"))) type ConfigFile struct {
HttpBindAddr string `json:"http_bind_addr"`
func handleHome(w http.ResponseWriter, r *http.Request) { SessionKey string `json:"session_key"`
fmt.Fprintf(w, "Hello, world!") LdapServerAddr string `json:"ldap_server_addr"`
} }
func main() { var configFlag = flag.String("config", "./config.json", "Configuration file path")
http.HandleFunc("/", handleHome)
bind_addr := os.Getenv("HTTP_BIND_ADDR") func readConfig() ConfigFile {
if bind_addr == "" { key_bytes := make([]byte, 32)
bind_addr = ":9991" n, err := rand.Read(key_bytes)
if err!= nil || n != 32 {
log.Fatal(err)
} }
err := http.ListenAndServe(bind_addr, nil) config_file := ConfigFile{
HttpBindAddr: ":9991",
SessionKey: base64.StdEncoding.EncodeToString(key_bytes),
LdapServerAddr: "127.0.0.1:389",
}
_, err = os.Stat(*configFlag)
if os.IsNotExist(err) {
// Generate default config file
log.Printf("Generating default config file as %s", *configFlag)
bytes, err := json.MarshalIndent(&config_file, "", " ")
if err != nil {
log.Fatal(err)
}
err = ioutil.WriteFile(*configFlag, bytes, 0644)
if err != nil {
log.Fatal(err)
}
return config_file
}
if err != nil {
log.Fatal(err)
}
bytes, err := ioutil.ReadFile(*configFlag)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(bytes, &config_file)
if err != nil {
log.Fatal(err)
}
return config_file
}
var store *sessions.CookieStore = nil
func main() {
flag.Parse()
config := readConfig()
store = sessions.NewCookieStore([]byte(config.SessionKey))
http.HandleFunc("/", handleHome)
err := http.ListenAndServe(config.HttpBindAddr, nil)
if err != nil { if err != nil {
log.Fatal("Cannot start http server: ", err) log.Fatal("Cannot start http server: ", err)
} }
} }
// Page handlers ----
func handleHome(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, world!")
}