-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
73 lines (64 loc) · 1.55 KB
/
main.go
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
package main
import (
"bytes"
_ "embed"
"fmt"
"html/template"
"log"
"net/http"
"strconv"
)
//go:embed index.html.template
var indexHTMLTemplate string
const rowsPerPage = 100
func main() {
templates := template.Must(template.New("").Funcs(template.FuncMap{
"lastIndex": func(length, index int) bool {
return index == (length - 1)
},
}).Parse(indexHTMLTemplate))
mux := http.NewServeMux()
mux.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
const initialID = 1
render(res, templates, Page{
Rows: setIDs(initialID, make([]Contact, rowsPerPage)),
NextURL: contactsURL(initialID),
})
})
mux.HandleFunc("/contacts", func(res http.ResponseWriter, req *http.Request) {
var page int
if p, err := strconv.Atoi(req.URL.Query().Get("page")); err == nil {
page = p
}
render(res, templates.Lookup("rows"), Page{
Rows: setIDs(page, make([]Contact, rowsPerPage)),
NextURL: contactsURL(page + 1),
})
})
log.Fatal(http.ListenAndServe(":8080", mux))
}
func contactsURL(page int) string {
return fmt.Sprintf("/contacts?page=%d", page)
}
func render(res http.ResponseWriter, t *template.Template, data any) {
var buf bytes.Buffer
if err := t.Execute(&buf, data); err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
res.WriteHeader(http.StatusOK)
_, _ = res.Write(buf.Bytes())
}
type Page struct {
Rows []Contact
NextURL string
}
type Contact struct {
ID int
}
func setIDs(n int, in []Contact) []Contact {
for i := range in {
in[i].ID = (n * 1000) + i
}
return in
}