aboutsummaryrefslogtreecommitdiff
path: root/main.go
diff options
context:
space:
mode:
authorAlex Auvolat <alex@adnab.me>2020-02-09 15:01:20 +0100
committerAlex Auvolat <alex@adnab.me>2020-02-09 15:01:20 +0100
commit8f5ab6cab3d21029d08e66c5ce99159bdd8a4c7f (patch)
tree87005e73a4873a799c174c265ca5118a6b3f0a72 /main.go
parentd12afb8a151b470552d01b4002839f34cc698c5e (diff)
downloadguichet-8f5ab6cab3d21029d08e66c5ce99159bdd8a4c7f.tar.gz
guichet-8f5ab6cab3d21029d08e66c5ce99159bdd8a4c7f.zip
Config file logic
Diffstat (limited to 'main.go')
-rw-r--r--main.go83
1 files changed, 73 insertions, 10 deletions
diff --git a/main.go b/main.go
index ce280ba..84eb402 100644
--- a/main.go
+++ b/main.go
@@ -2,29 +2,92 @@ package main
import (
"os"
+ "flag"
+ "fmt"
"log"
"net/http"
- "fmt"
+ "io/ioutil"
+ "encoding/json"
+ "encoding/base64"
+ "crypto/rand"
"github.com/gorilla/sessions"
)
-var store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY")))
+type ConfigFile struct {
+ HttpBindAddr string `json:"http_bind_addr"`
+ SessionKey string `json:"session_key"`
+ LdapServerAddr string `json:"ldap_server_addr"`
+}
-func handleHome(w http.ResponseWriter, r *http.Request) {
- fmt.Fprintf(w, "Hello, world!")
+var configFlag = flag.String("config", "./config.json", "Configuration file path")
+
+func readConfig() ConfigFile {
+ key_bytes := make([]byte, 32)
+ n, err := rand.Read(key_bytes)
+ if err!= nil || n != 32 {
+ log.Fatal(err)
+ }
+
+ 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() {
- http.HandleFunc("/", handleHome)
+ flag.Parse()
- bind_addr := os.Getenv("HTTP_BIND_ADDR")
- if bind_addr == "" {
- bind_addr = ":9991"
- }
+ config := readConfig()
+ store = sessions.NewCookieStore([]byte(config.SessionKey))
+
+ http.HandleFunc("/", handleHome)
- err := http.ListenAndServe(bind_addr, nil)
+ err := http.ListenAndServe(config.HttpBindAddr, nil)
if err != nil {
log.Fatal("Cannot start http server: ", err)
}
}
+
+// Page handlers ----
+
+func handleHome(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintf(w, "Hello, world!")
+}