ThePlaceHolders/server.go

79 lines
2.1 KiB
Go
Raw Normal View History

2024-09-25 18:05:04 -05:00
package main
import (
2024-10-16 16:43:13 -05:00
"encoding/json"
2024-10-11 05:36:08 -05:00
"flag"
2024-09-25 18:05:04 -05:00
"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
)
2024-10-16 16:43:13 -05:00
const CANVAS_WIDTH = 1000
const CANVAS_HEIGHT = 1000
type Canvas struct {
Data [CANVAS_WIDTH * CANVAS_HEIGHT]byte `json:"data"`
Width int `json:"width"`
Height int `json:"height"`
}
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-10-16 16:43:13 -05:00
Canvas Canvas
}
func (s *Server) canvas(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(s.canvas)
2024-09-25 19:05:33 -05:00
}
2024-09-26 01:11:22 -05:00
func main() {
2024-10-16 16:43:13 -05:00
// Grab command line arguments
2024-10-11 05:36:08 -05:00
ipFlag := flag.String("ip", "127.0.0.1", "IP address to receive traffic from")
portFlag := flag.String("port", "8080", "Port to receive traffic from")
flag.Parse()
address := *ipFlag
port := *portFlag
2024-09-26 01:11:22 -05:00
// 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-10-16 16:43:13 -05:00
Canvas: Canvas{},
}
for x := 0; x < CANVAS_WIDTH; x++ {
for y := 0; y < CANVAS_HEIGHT; y++ {
server.Canvas.Data[y*CANVAS_HEIGHT+x] = byte(CANVAS_WIDTH / x)
}
2024-09-25 19:05:33 -05:00
}
2024-10-16 16:43:13 -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-29 19:05:16 -05:00
http.HandleFunc("/secret", server.secret)
2024-10-16 16:43:13 -05:00
http.HandleFunc("/canvas", canvas)
2024-09-25 18:05:04 -05:00
// Start web server at 127.0.0.1:8080
2024-10-11 05:36:08 -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
}
}