~mendelmaleh/dummy

ref: 67121cb151871d5b36e6e29fefbfbd9c76e5b99d dummy/options.go -rw-r--r-- 1.7 KiB
67121cb1Mendel E Normalize in opt.FromForm directly 1 year, 6 months ago
                                                                                
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
package main

import (
	"image/color"
	"net/url"
	"strconv"
)

type Options struct {
	// image
	Width, Height int
	Pattern       string
	Colors        []color.RGBA

	// web
	Desc string
}

// to be used only with dopt.Copy(), otherwise the default colors can be changed.
var dopt = &Options{
	// image
	Width:   200,
	Height:  200,
	Pattern: "plain",
	Colors: []color.RGBA{
		color.RGBA{0x24, 0x29, 0x33, 0xff},
		color.RGBA{0xec, 0xef, 0xf4, 0xff},
	},

	// web
	Desc: "Dummy image generator",
}

// FromForm gets values from the form (which includes the url encoded query)
// and applies them to our Options. To ne used with r.Form after r.ParseForm().
func (opt *Options) FromForm(form url.Values) error {
	// image
	if w, ok := form["width"]; ok {
		i, err := strconv.Atoi(w[0])
		if err != nil {
			return err
		}

		opt.Width = i
	}

	if h, ok := form["height"]; ok {
		i, err := strconv.Atoi(h[0])
		if err != nil {
			return err
		}

		opt.Height = i
	}

	if p, ok := form["pattern"]; ok {
		opt.Pattern = p[0]
	}

	if colors, ok := form["color"]; ok {
		for i, h := range colors {
			c, err := Hex(h)
			if err != nil {
				return err
			}

			opt.Colors[i] = c
		}
	}

	// web
	if d, ok := form["desc"]; ok {
		opt.Desc = d[0]
	}

	// apply limits and hacks
	opt.Normalize()

	return nil
}

// Copy so that the original options don't change (essentially a deep copy).
func (opt Options) Copy() (copt Options) {
	// copy all the fields
	copt = opt

	// deep copy for slices
	copt.Colors = make([]color.RGBA, len(opt.Colors))
	copy(copt.Colors, opt.Colors)

	return copt
}

// Normalize our Options, implement limits and workarounds.
func (opt *Options) Normalize() {
	// limit width to 600 for now
	if opt.Width > 600 {
		opt.Width = 600
	}
}