/
client.go
124 lines (113 loc) · 2.52 KB
/
client.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
package templater
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"path"
"gopkg.in/yaml.v2"
)
type option func(*remoteClient)
type remoteClient struct {
BaseURL *url.URL
SettingYmlName string
Client *http.Client
}
type RemoteAppSetting struct {
Name string `yaml:"name"`
BgPath string `yaml:"bg-file-path"`
Templates []string `yaml:"templates"`
}
func NewRemoteClient(urlStr string, ops ...option) (*remoteClient, error) {
dir, filename := path.Split(urlStr)
baseURL, err := url.Parse(dir)
if err != nil {
return nil, err
}
c := &remoteClient{
BaseURL: baseURL,
SettingYmlName: filename,
Client: http.DefaultClient,
}
for _, op := range ops {
op(c)
}
return c, nil
}
func WithHttpClient(client *http.Client) option {
return func(c *remoteClient) {
c.Client = client
}
}
func (rc *remoteClient) fetchSettingFromYaml() (*RemoteAppSetting, error) {
resp, err := rc.Client.Get(fmt.Sprintf("%s/%s", rc.BaseURL.String(), rc.SettingYmlName))
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
ras := &RemoteAppSetting{}
err = yaml.Unmarshal(data, &ras)
if err != nil {
return nil, err
}
return ras, nil
}
func (rc *remoteClient) RemoteSettingToAppTemplate() (*AppTemplate, error) {
setting, err := rc.fetchSettingFromYaml()
if err != nil {
return nil, err
}
resp, err := rc.Client.Get(fmt.Sprintf("%s/%s", rc.BaseURL.String(), setting.BgPath))
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
appTemplate := new(AppTemplate)
appTemplate.Name = setting.Name
appTemplate.Bg = string(data)
templates := make([]*Templater, len(setting.Templates))
for i, v := range setting.Templates {
rt := remoteTmpl{
Client: rc.Client,
Path: v,
BaseURL: rc.BaseURL,
}
dir, filename := path.Split(v)
templates[i] = &Templater{
rt,
dir,
filename,
}
}
appTemplate.Tmpls = templates
return appTemplate, nil
}
type remoteTmpl struct {
Client *http.Client
Path string
BaseURL *url.URL
}
func (rt remoteTmpl) String() (string, error) {
resp, err := rt.Client.Get(fmt.Sprintf("%s/%s", rt.BaseURL.String(), rt.Path))
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", errors.New("cannot get this file.")
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(data), nil
}