ThePlaceHolders/server.go

50 lines
1.2 KiB
Go
Raw Normal View History

2024-09-25 18:05:04 -05:00
package main
import (
"fmt"
2024-09-26 01:11:22 -05:00
"log"
2024-09-25 18:05:04 -05:00
"net/http"
2024-09-26 01:11:22 -05:00
"github.com/gorilla/sessions"
2024-09-25 18:05:04 -05:00
)
const ADDRESS = "127.0.0.1"
const PORT = "8080"
2024-09-26 01:11:22 -05:00
type Server struct {
// Registered user information
Users map[string]UserData
// Login sessions
2024-09-26 01:11:22 -05:00
Sessions *sessions.CookieStore
2024-09-25 19:05:33 -05:00
}
2024-09-26 01:11:22 -05:00
func main() {
// Create server object
2024-09-27 14:37:49 -05:00
secret := []byte("super-secret-key")
2024-09-26 01:11:22 -05:00
server := Server{
Users: make(map[string]UserData),
Sessions: sessions.NewCookieStore(secret),
2024-09-25 19:05:33 -05:00
}
2024-09-25 18:05:04 -05:00
// Host static files
static_files := http.FileServer(http.Dir("static/"))
http.Handle("/", static_files)
2024-09-27 14:37:49 -05:00
// Redirect .html to clean URL
http.Handle("/register.html", http.RedirectHandler("/register", 301))
http.Handle("/login.html", http.RedirectHandler("/login", 301))
// Handle user authentication
http.HandleFunc("/register", server.handle_register)
http.HandleFunc("/login", server.handle_login)
http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
server.handle_logout(w, r)
http.Redirect(w, r, "/", http.StatusFound)
})
2024-09-25 18:05:04 -05:00
// Start web server at 127.0.0.1:8080
2024-09-26 01:11:22 -05:00
fmt.Printf("Listening to %s on port %s...\n", ADDRESS, PORT)
err := http.ListenAndServe(ADDRESS+":"+PORT, nil)
2024-09-25 18:05:04 -05:00
// Print any errors
if err != nil {
2024-09-26 01:11:22 -05:00
fmt.Println("Error starting server:")
log.Fatal(err)
2024-09-25 18:05:04 -05:00
}
}