Adding config.json

This commit is contained in:
Jarkko Toivanen 2024-12-28 00:57:15 +02:00
parent fac0e5a7a3
commit 78618fc1e8
Signed by: jt
GPG key ID: 9151B109B73ECAD5
3 changed files with 31 additions and 1 deletions

1
.gitignore vendored
View file

@ -1,2 +1,3 @@
snuffler-web snuffler-web
database.db database.db
config.json

3
config.json.example Normal file
View file

@ -0,0 +1,3 @@
{
"port": 6900
}

28
main.go
View file

@ -2,13 +2,20 @@ package main
import ( import (
"database/sql" "database/sql"
"encoding/json"
"fmt"
"html/template" "html/template"
"log" "log"
"net/http" "net/http"
"os"
_ "modernc.org/sqlite" _ "modernc.org/sqlite"
) )
type Config struct {
Port uint
}
type user struct { type user struct {
id uint id uint
name string name string
@ -57,14 +64,33 @@ var db *sql.DB
func main() { func main() {
var err error var err error
// Load config
fmt.Println("Loading config.json")
cfgfile, err := os.Open("config.json")
if err != nil {
log.Fatal("Error reading config.json!")
return
}
defer cfgfile.Close()
decoder := json.NewDecoder(cfgfile)
Config := Config{}
err = decoder.Decode(&Config)
if err != nil {
log.Fatal("Can't decode config.json!")
return
}
db, err = sql.Open("sqlite", "database.db") db, err = sql.Open("sqlite", "database.db")
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
fmt.Printf("Starting listener on :%v", Config.Port)
http.Handle("/static/", http.FileServer(http.Dir("./"))) http.Handle("/static/", http.FileServer(http.Dir("./")))
http.HandleFunc("/", httpRootHandler) http.HandleFunc("/", httpRootHandler)
err = http.ListenAndServe(":6900", nil) err = http.ListenAndServe(fmt.Sprintf(":%v", Config.Port), nil)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }