gonotes/cmd/server/main.go

77 lines
1.7 KiB
Go
Raw Normal View History

package main
import (
2025-07-30 09:35:01 +01:00
"crypto/rand"
"flag"
"log"
"net"
"net/http"
2025-06-26 22:42:03 +01:00
"os"
"time"
2025-06-01 21:27:08 +01:00
"forgejo.gwairfelin.com/max/gonotes/internal/conf"
"forgejo.gwairfelin.com/max/gonotes/internal/middleware"
2025-06-01 21:27:08 +01:00
"forgejo.gwairfelin.com/max/gonotes/internal/notes/views"
)
func main() {
var confFile string
2025-07-30 09:35:01 +01:00
cache := make(map[string]string, 20)
2025-06-24 19:48:55 +01:00
flag.StringVar(&confFile, "c", "/etc/gonotes/conf.toml", "Specify path to config file.")
flag.Parse()
conf.LoadConfig(confFile)
2025-06-26 22:42:03 +01:00
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)
2025-07-30 09:35:01 +01:00
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)))
2025-07-30 09:35:01 +01:00
router.Handle("/notes/", middleware.SessionMiddleware(cache, middleware.LoggingMiddleware(http.StripPrefix("/notes", notesRouter))))
2025-01-28 22:08:01 +00:00
router.Handle(
2025-06-25 21:30:57 +01:00
"/static/",
middleware.LoggingMiddleware(
middleware.StaticEtagMiddleware(
*etag,
http.FileServer(http.FS(conf.Static)),
),
2025-01-28 22:08:01 +00:00
),
)
listener, err := net.Listen(conf.Conf.Protocol, conf.Conf.Address)
if err != nil {
log.Fatal(err)
}
log.Fatal(http.Serve(listener, router))
}