-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_request.go
136 lines (115 loc) · 2.51 KB
/
generate_request.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"net/http"
"os"
"github.com/golang/freetype/truetype"
"github.com/inconshreveable/log15"
"github.com/rs/xid"
"golang.org/x/image/font"
"golang.org/x/image/font/gofont/goregular"
"golang.org/x/image/math/fixed"
)
type generateRequest struct {
r *http.Request
logger log15.Logger
descriptions map[string]description
base string
question string
answers []string
uid string
err error
desc description
image *image.RGBA
font *truetype.Font
}
func (r *generateRequest) init() {
r.uid = xid.New().String()
r.logger = r.logger.New("uid", r.uid)
}
func (r *generateRequest) readPayload() {
if r.err != nil {
return
}
r.r.ParseForm()
r.base = r.r.Form.Get("base")
if r.base == "" {
r.base = "qvgdm"
}
r.question = r.r.Form.Get("question")
r.answers = r.r.Form["answers"]
var ok bool
r.desc, ok = r.descriptions[r.base]
if !ok {
r.err = fmt.Errorf(`unknown base %q`, r.base)
return
}
}
// getBase open and decode the base image, and convert it into a RGBA image
// suitable to be modified.
func (r *generateRequest) getBase() {
if r.err != nil {
return
}
f, err := os.Open(r.desc.Base)
if err != nil {
r.err = wrap(err, "opening base image")
return
}
defer f.Close()
src, _, err := image.Decode(f)
if err != nil {
r.err = wrap(err, "decoding base image")
return
}
b := src.Bounds()
r.image = image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
draw.Draw(r.image, r.image.Bounds(), src, b.Min, draw.Src)
}
// Get the font for this image.
func (r *generateRequest) getFont() {
if r.err != nil {
return
}
var err error
r.font, err = truetype.Parse(goregular.TTF)
if err != nil {
r.err = wrap(err, "loading font")
return
}
}
func (r *generateRequest) writeQuestion() {
if r.err != nil {
return
}
// Draw the question.
d := &font.Drawer{
Dst: r.image,
Src: image.NewUniform(color.White),
Face: truetype.NewFace(r.font, &truetype.Options{
Size: r.desc.Question.Size,
}),
Dot: fixed.P(r.desc.Question.X, r.desc.Question.Y),
}
d.DrawString(r.question)
}
func (r *generateRequest) writeAnswers() {
if r.err != nil {
return
}
// Draw the answers.
for i := 0; i < len(r.answers) && i < len(r.desc.Answers); i++ {
d := &font.Drawer{
Dst: r.image,
Src: image.NewUniform(color.White),
Face: truetype.NewFace(r.font, &truetype.Options{
Size: r.desc.Answers[i].Size,
}),
Dot: fixed.P(r.desc.Answers[i].X, r.desc.Answers[i].Y),
}
d.DrawString(r.answers[i])
}
}