summaryrefslogtreecommitdiff
path: root/main.go
blob: cef556ea565cdcd89482a8d731badf066a722f64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main

import (
	"database/sql"
	"flag"
	"log"
	"net"
	"net/http"
	"os"
	"strconv"

	"github.com/gorilla/handlers"
	"github.com/gorilla/schema"

	"gosten/model"
	"gosten/templ"
)

// flags
var (
	port uint64
	host string
)

func init() {
	flag.StringVar(&host, "h", "localhost", "address to listen on")
	flag.Uint64Var(&port, "p", 8080, "port to listen on")
}

var Q *model.Queries
var s *schema.Decoder

func main() {
	flag.Parse()

	db, err := sql.Open(driverName, "test.sqlite")
	if err != nil {
		log.Fatal(err)
	}

	Q = model.New(db)
	s = schema.NewDecoder()

	mux := http.NewServeMux()

	mux.HandleFunc("/{$}", showTemplate("index", nil))
	mux.HandleFunc("GET /login", showTemplate("login", User{}))
	mux.HandleFunc("POST /login", handleLogin)

	handler := handlers.CombinedLoggingHandler(os.Stderr, mux)
	handler = handlers.ProxyHeaders(handler)

	address := net.JoinHostPort(host, strconv.FormatUint(port, 10))
	log.Fatal(http.ListenAndServe(address, handler))
}

type User struct {
	Name     string `form:"options=required"`
	Password string `form:"type=password;options=required"`
}

func showTemplate(tpl string, data any) http.HandlerFunc {
	return func(w http.ResponseWriter, _ *http.Request) {
		if err := templ.Lookup(tpl).Execute(w, data); err != nil {
			log.Panicf("Executing '%s' with %+v: %v", tpl, data, err)
		}
	}
}

func handleLogin(w http.ResponseWriter, r *http.Request) {
	u := User{}
	if err := r.ParseForm(); err != nil {
		log.Panic("Parsing form: ", err)
	}
	if err := s.Decode(&u, r.PostForm); err != nil {
		log.Panic("Decoding form: ", err)
	}

	showTemplate("login2", u).ServeHTTP(w, r)
}