File: main.go

package info (click to toggle)
golang-github-valyala-quicktemplate 1.8.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 492 kB
  • sloc: makefile: 16; xml: 15
file content (77 lines) | stat: -rw-r--r-- 1,721 bytes parent folder | download | duplicates (3)
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
// The following line is needed for generating go code from templates
// with `go generate`.
// See https://blog.golang.org/generate for more info.
// Quicktemplate compiler (qtc) must be installed before running
// `go generate`:
//
//     go get -u github.com/valyala/quicktemplate/qtc
//
//go:generate qtc -dir=templates
package main

import (
	"fmt"
	"log"
	"math/rand"

	"github.com/valyala/fasthttp"
	"github.com/valyala/quicktemplate/examples/basicserver/templates"
)

func main() {
	log.Printf("starting the server at http://localhost:8080 ...")
	err := fasthttp.ListenAndServe("localhost:8080", requestHandler)
	if err != nil {
		log.Fatalf("unexpected error in server: %s", err)
	}
}

func requestHandler(ctx *fasthttp.RequestCtx) {
	switch string(ctx.Path()) {
	case "/":
		mainPageHandler(ctx)
	case "/table":
		tablePageHandler(ctx)
	default:
		errorPageHandler(ctx)
	}
	ctx.SetContentType("text/html; charset=utf-8")
}

func mainPageHandler(ctx *fasthttp.RequestCtx) {
	p := &templates.MainPage{
		CTX: ctx,
	}
	templates.WritePageTemplate(ctx, p)
}

func tablePageHandler(ctx *fasthttp.RequestCtx) {
	rowsCount := ctx.QueryArgs().GetUintOrZero("rowsCount")
	if rowsCount == 0 {
		rowsCount = 10
	}
	p := &templates.TablePage{
		Rows: generateRows(rowsCount),
	}
	templates.WritePageTemplate(ctx, p)
}

func errorPageHandler(ctx *fasthttp.RequestCtx) {
	p := &templates.ErrorPage{
		Path: ctx.Path(),
	}
	templates.WritePageTemplate(ctx, p)
	ctx.SetStatusCode(fasthttp.StatusBadRequest)
}

func generateRows(rowsCount int) []string {
	var rows []string
	for i := 0; i < rowsCount; i++ {
		r := fmt.Sprintf("row %d", i)
		if rand.Intn(20) == 0 {
			r = "bingo"
		}
		rows = append(rows, r)
	}
	return rows
}