package main import ( "encoding/gob" "log" "net/http" "strings" lishwist "lishwist/core" "lishwist/http/api" "lishwist/http/env" "lishwist/http/router" "lishwist/http/routing" "lishwist/http/session" ) func prefixMovedPermanently(before, after string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { suffix := strings.TrimPrefix(r.RequestURI, before) http.Redirect(w, r, after+suffix, http.StatusMovedPermanently) } } func main() { gob.Register(&api.RegisterProps{}) gob.Register(&api.LoginProps{}) err := lishwist.Init(env.DatabaseFile) if err != nil { log.Fatalf("Failed to init Lishwist: %s\n", err) } store := session.NewInMemoryStore([]byte(env.SessionSecret)) store.Options.MaxAge = 86_400 // 24 hours in seconds store.Options.Secure = !env.InDev store.Options.HttpOnly = true r := router.New(store) r.Public.HandleFunc("GET /", routing.Login) r.Public.HandleFunc("GET /groups/{groupReference}", routing.PublicGroup) r.Public.HandleFunc("GET /lists/{userReference}", routing.PublicWishlist) r.Public.HandleFunc("GET /register", routing.Register) r.Public.HandleFunc("POST /", routing.LoginPost) r.Public.HandleFunc("POST /register", routing.RegisterPost) r.Private.HandleFunc("GET /", routing.NotFound) r.Private.HandleFunc("GET /groups", routing.ExpectAppSession(routing.Groups)) r.Private.HandleFunc("GET /groups/{groupReference}", routing.ExpectAppSession(routing.Group)) r.Private.HandleFunc("GET /lists/{userReference}", routing.ExpectAppSession(routing.ForeignWishlist)) r.Private.HandleFunc("GET /users", routing.ExpectAppSession(routing.Users)) r.Private.HandleFunc("GET /users/{userReference}", routing.ExpectAppSession(routing.User)) r.Private.HandleFunc("GET /{$}", routing.ExpectAppSession(routing.Home)) r.Private.HandleFunc("POST /groups/{groupReference}", routing.ExpectAppSession(routing.GroupPost)) r.Private.HandleFunc("POST /list/{userReference}", routing.ExpectAppSession(routing.ForeignWishlistPost)) r.Private.HandleFunc("POST /logout", routing.LogoutPost) r.Private.HandleFunc("POST /users/{userReference}", routing.ExpectAppSession(routing.UserPost)) r.Private.HandleFunc("POST /{$}", routing.ExpectAppSession(routing.HomePost)) // Deprecated http.Handle("GET /group/{groupReference}", prefixMovedPermanently("/group/", "/groups/")) http.Handle("GET /list/{userReference}", prefixMovedPermanently("/list/", "/lists/")) http.Handle("/", r) log.Printf("Running at http://127.0.0.1:%s\n", env.ServePort) err = http.ListenAndServe(":"+env.ServePort, nil) if err != nil { log.Fatalln("Failed to listen and server:", err) } }