chore: added templating
d34e0d24
3 file(s) · +35 −1
Binary file — no preview.
| 1 | 1 | package main |
|
| 2 | 2 | ||
| 3 | 3 | import ( |
|
| 4 | + | "embed" |
|
| 4 | 5 | "fmt" |
|
| 5 | 6 | "log" |
|
| 7 | + | "html/template" |
|
| 6 | 8 | "net/http" |
|
| 7 | 9 | "os" |
|
| 8 | 10 | ) |
|
| 9 | 11 | ||
| 12 | + | // Plan |
|
| 13 | + | // - [ ] Serve robots.txt with noindex |
|
| 14 | + | // - [/] Serve root path html with babbler and links to new paths |
|
| 15 | + | // - [ ] Serve dynamic path that takes in path param to serve babbler and more links |
|
| 16 | + | // - [ ] Slow down responses |
|
| 17 | + | ||
| 10 | 18 | var portEnv = os.Getenv("PORT") |
|
| 11 | 19 | ||
| 20 | + | //go:embed templates/*.html |
|
| 21 | + | var templatesFS embed.FS |
|
| 22 | + | ||
| 23 | + | type PageData struct { |
|
| 24 | + | Title string |
|
| 25 | + | Items []string |
|
| 26 | + | } |
|
| 27 | + | ||
| 28 | + | var tmpl = template.Must(template.ParseFS(templatesFS, "templates/*.html")) |
|
| 29 | + | ||
| 12 | 30 | func indexHandler(writer http.ResponseWriter, req *http.Request) { |
|
| 13 | - | fmt.Fprintf(writer, "hello world\n") |
|
| 31 | + | data := PageData{ |
|
| 32 | + | Title: "Babbler", |
|
| 33 | + | Items: []string{"First link", "second link", "third link"}, |
|
| 34 | + | } |
|
| 35 | + | if err := tmpl.ExecuteTemplate(writer, "index.html", data); err != nil { |
|
| 36 | + | http.Error(writer, "Internal server error", http.StatusInternalServerError) |
|
| 37 | + | } |
|
| 14 | 38 | } |
|
| 15 | 39 | ||
| 16 | 40 | func logRequest(handler http.Handler) http.Handler { |
| 1 | + | <!DOCTYPE html> |
|
| 2 | + | <html> |
|
| 3 | + | <head> |
|
| 4 | + | <meta charset="UTF-8"> |
|
| 5 | + | <title>{{.Title}}</title> |
|
| 6 | + | </head> |
|
| 7 | + | <body> |
|
| 8 | + | {{range .Items}}<div>{{ . }}</div>{{else}}<div><strong>no rows</strong></div>{{end}} |
|
| 9 | + | </body> |
|
| 10 | + | </html> |