From 3c80ec88643c39959b4710c7abaca2f666ac1163 Mon Sep 17 00:00:00 2001 From: Romain de Laage Date: Sun, 28 Feb 2021 15:19:15 +0100 Subject: [PATCH] Can be configured --- config.json | 6 ++++++ server.go | 55 +++++++++++++++++++++++++++++++++++++++++------------ 2 files changed, 49 insertions(+), 12 deletions(-) create mode 100644 config.json diff --git a/config.json b/config.json new file mode 100644 index 0000000..08873f0 --- /dev/null +++ b/config.json @@ -0,0 +1,6 @@ +{ + "listen": "0.0.0.0:1965", + "cert_path": "cert.pem", + "key_path": "key.rsa", + "base_url": "https://mamot.fr" +} diff --git a/server.go b/server.go index 40a5601..a3a8453 100644 --- a/server.go +++ b/server.go @@ -5,8 +5,8 @@ import ( "log" "net" "net/http" + "os" "fmt" - "mime" "encoding/json" "io/ioutil" "strings" @@ -20,17 +20,48 @@ type Blog struct { Date string `json:"created_at"` } +type Config struct { + Listen string `json:"listen"` + CertPath string `json:"cert_path"` + KeyPath string `json:"key_path"` + BaseURL string `json:"base_url"` +} + func main() { - err := mime.AddExtensionType(".gmi", "text/gemini") - if err != nil { - log.Fatalln("mime: %s", err) + config := getConfig() + + listener := listen(config.Listen, config.CertPath, config.KeyPath) + log.Println("Server successfully started") + log.Println("Server is listening at " + config.Listen) + + serve(listener, config.BaseURL) +} + +func getConfig() Config { + configPath := os.Getenv("MASTOGEM_CONFIG_PATH") + if configPath == "" { + log.Println("MASTOGEM_CONFIG_PATH was not set, using default settings") + + config := Config{ + Listen: "127.0.0.1:1965", + CertPath: "cert.pem", + KeyPath: "key.rsa", + BaseURL: "https://mamot.fr", + } + + return config } - listener := listen("0.0.0.0:1965", "cert.pem", "key.rsa") - log.Println("Server successfully started") - log.Println("Server is listening at 0.0.0.0:1956") + configFile, err := ioutil.ReadFile(configPath) + if err != nil { + log.Fatalln("config file: %s", err) + } - serve(listener) + var config Config + + json.Unmarshal(configFile, &config) + + return config } func listen(address, certFile, keyFile string) net.Listener { @@ -53,21 +84,21 @@ func listen(address, certFile, keyFile string) net.Listener { return listener } -func serve(listener net.Listener) { +func serve(listener net.Listener, baseURL string) { for { conn, err := listener.Accept() if err != nil { log.Println(err) } - go handleConn(conn.(*tls.Conn)) + go handleConn(conn.(*tls.Conn), baseURL) } } -func handleConn(conn *tls.Conn) { +func handleConn(conn *tls.Conn, baseURL string) { defer conn.Close() - blogs := getBlog("https://mamot.fr", "138624") + blogs := getBlog(baseURL, "138624") _, err := fmt.Fprintf(conn, "20 text/gemini\r\n# Picasoft account toots\n") if err != nil {