gonotes/cmd/server/main.go

76 lines
1.7 KiB
Go

package main
import (
"crypto/rand"
"flag"
"log"
"net"
"net/http"
"os"
"time"
"forgejo.gwairfelin.com/max/gonotes/internal/conf"
"forgejo.gwairfelin.com/max/gonotes/internal/middleware"
"forgejo.gwairfelin.com/max/gonotes/internal/notes/views"
)
func main() {
var confFile string
cache := make(map[string]string, 20)
flag.StringVar(&confFile, "c", "/etc/gonotes/conf.toml", "Specify path to config file.")
flag.Parse()
conf.LoadConfig(confFile)
log.SetOutput(os.Stdout)
router := http.NewServeMux()
notesRouter := views.GetRoutes("/notes")
cacheExpiration, err := time.ParseDuration("24h")
if err != nil {
log.Fatal(err)
}
etag := middleware.NewETag("static", cacheExpiration)
if !conf.Conf.Production {
router.HandleFunc("/login/", func(w http.ResponseWriter, r *http.Request) {
user := r.FormValue("user")
log.Printf("Trying to log in %s", user)
sessionID := rand.Text()
cache[sessionID] = user
// TODO: omg remove this
log.Printf("Session id is %s", sessionID)
cookie := http.Cookie{
Name: "id", Value: sessionID, MaxAge: 3600,
Secure: true, HttpOnly: true, Path: "/",
}
http.SetCookie(w, &cookie)
http.Redirect(w, r, "/notes/", http.StatusFound)
})
}
router.Handle("/", middleware.LoggingMiddleware(http.RedirectHandler("/notes/", http.StatusFound)))
router.Handle("/notes/", middleware.SessionMiddleware(cache, middleware.LoggingMiddleware(http.StripPrefix("/notes", notesRouter))))
router.Handle(
"/static/",
middleware.LoggingMiddleware(
middleware.StaticEtagMiddleware(
*etag,
http.FileServer(http.FS(conf.Static)),
),
),
)
listener, err := net.Listen(conf.Conf.Protocol, conf.Conf.Address)
if err != nil {
log.Fatal(err)
}
log.Fatal(http.Serve(listener, router))
}