forked from SoCloz/goprismic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
view.go
58 lines (52 loc) · 1.33 KB
/
view.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
package image
import (
"fmt"
"reflect"
)
// An image view
type View struct {
Url string `json:"url"`
Alt string `json:"alt,omitempty"`
Copyright string `json:"copyright,omitempty"`
Dimensions struct {
Width int `json:"width"`
Height int `json:"height"`
} `json:"dimensions"`
}
func (i *View) Decode(enc interface{}) error {
dec, ok := enc.(map[string]interface{})
if !ok {
return fmt.Errorf("unable to decode image view : %+v is a %s, not a map", enc, reflect.TypeOf(enc))
}
if v, found := dec["url"]; found {
i.Url = v.(string)
}
if v, found := dec["alt"]; found {
i.Alt = v.(string)
}
if v, found := dec["copyright"]; found {
i.Copyright = v.(string)
}
if d, found := dec["dimensions"]; found {
dim, ok := d.(map[string]interface{})
if !ok {
return fmt.Errorf("%+v is not a map", d)
}
if v, found := dim["width"]; found && v != nil {
i.Dimensions.Width = int(v.(float64))
}
if v, found := dim["height"]; found && v != nil {
i.Dimensions.Height = int(v.(float64))
}
}
return nil
}
func (i *View) AsText() string {
return i.Url
}
func (i *View) AsHtml() string {
return fmt.Sprintf("<img src=\"%s\" width=\"%d\" height=\"%d\"/>", i.Url, i.Dimensions.Width, i.Dimensions.Height)
}
func (i *View) Ratio() float64 {
return float64(i.Dimensions.Width) / float64(i.Dimensions.Height)
}