107 lines
2.3 KiB
Go
107 lines
2.3 KiB
Go
package web
|
|
|
|
import (
|
|
"embed"
|
|
"f00860/kartograph-map-editor/pkg/generator"
|
|
"fmt"
|
|
"html/template"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
)
|
|
|
|
//go:embed templates
|
|
var templateFiles embed.FS
|
|
|
|
//go:embed static
|
|
var staticFiles embed.FS
|
|
|
|
func Start(address string, port int) {
|
|
http.Handle("/static/", http.FileServer(http.FS(staticFiles)))
|
|
http.HandleFunc("/", indexHandler)
|
|
http.HandleFunc("/map.svg", mapHandler)
|
|
http.HandleFunc("/print", printHandler)
|
|
|
|
addr := address + ":" + strconv.Itoa(port)
|
|
|
|
log.Printf("Server started on %v ...", addr)
|
|
err := http.ListenAndServe(addr, nil)
|
|
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func worldFromRequest(req *http.Request) (generator.World, error) {
|
|
size, err := strconv.Atoi(req.URL.Query().Get("s"))
|
|
if err != nil {
|
|
size = 11
|
|
}
|
|
seed := req.URL.Query().Get("seed")
|
|
if seed == "" {
|
|
seed = time.Now().String()
|
|
}
|
|
wastelands, err := strconv.Atoi(req.URL.Query().Get("w"))
|
|
if err != nil {
|
|
wastelands = 7
|
|
}
|
|
mountains, err := strconv.Atoi(req.URL.Query().Get("m"))
|
|
if err != nil {
|
|
mountains = 5
|
|
}
|
|
ruins, err := strconv.Atoi(req.URL.Query().Get("r"))
|
|
if err != nil {
|
|
ruins = 6
|
|
}
|
|
|
|
return generator.New(size, wastelands, mountains, ruins, seed)
|
|
}
|
|
|
|
func mapHandler(w http.ResponseWriter, req *http.Request) {
|
|
log.Printf("GET /map.svg?%v (%v)", req.URL.Query().Encode(), req.RemoteAddr)
|
|
|
|
var SVGContent string
|
|
|
|
world, err := worldFromRequest(req)
|
|
if err != nil {
|
|
SVGContent = generator.ErrorSVG(err, 100, 100)
|
|
} else {
|
|
SVGContent = world.SVG()
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "image/svg+xml")
|
|
w.Header().Set("Content-Length", strconv.Itoa(len(SVGContent)))
|
|
io.WriteString(w, SVGContent)
|
|
}
|
|
|
|
func printHandler(w http.ResponseWriter, req *http.Request) {
|
|
log.Printf("GET /print?%v (%v)", req.URL.Query().Encode(), req.RemoteAddr)
|
|
|
|
world, err := worldFromRequest(req)
|
|
if err != nil {
|
|
fmt.Print(err)
|
|
return
|
|
}
|
|
tpl, err := template.ParseFS(templateFiles, "templates/print.tpl.html")
|
|
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
tpl.Execute(w, world)
|
|
}
|
|
|
|
func indexHandler(w http.ResponseWriter, req *http.Request) {
|
|
seed := generator.RandomSeed()
|
|
world, _ := generator.New(11, 7, 5, 6, seed)
|
|
log.Printf("GET / (%v) Seed: %v", req.RemoteAddr, seed)
|
|
tpl, err := template.ParseFS(templateFiles, "templates/index.tpl.html")
|
|
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
tpl.Execute(w, world)
|
|
}
|