This repository has been archived by the owner on Sep 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
base.go
326 lines (271 loc) · 6.57 KB
/
base.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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
// Copyright 2016 The go-ego Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// https://github.com/go-ego/ego/blob/master/LICENSE
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
package ego
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"net/url"
"os"
"strings"
"time"
)
func Try(fun func(), handler func(interface{})) {
defer func() {
if err := recover(); err != nil {
handler(err)
}
}()
fun()
}
func CheckErr(err error) {
if err != nil {
panic(err)
}
}
func ListFile(dirPth string, suffix string) (files []string, err error) {
files = make([]string, 0, 10)
dir, err := ioutil.ReadDir(dirPth)
if err != nil {
return nil, err
}
PthSep := string(os.PathSeparator)
suffix = strings.ToUpper(suffix)
for _, fi := range dir {
if fi.IsDir() {
continue
}
if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) {
files = append(files, dirPth+PthSep+fi.Name())
}
}
return files, nil
}
func ListDir(dirPth string, suffix string) (files []string, err error) {
files = make([]string, 0, 10)
dir, err := ioutil.ReadDir(dirPth)
if err != nil {
return nil, err
}
PthSep := string(os.PathSeparator)
suffix = strings.ToUpper(suffix)
for _, fi := range dir {
if !fi.IsDir() {
continue
}
if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) {
files = append(files, dirPth+PthSep+fi.Name())
}
}
return files, nil
}
// Get http get
func Get(apiUrl string, params url.Values) (rs []byte, err error) {
var Url *url.URL
Url, err = url.Parse(apiUrl)
if err != nil {
log.Printf("analytic url error:\r\n%v", err)
return nil, err
}
// URLEncode
Url.RawQuery = params.Encode()
resp, err := http.Get(Url.String())
if err != nil {
log.Println("http get error:", err)
return nil, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
// Post http post, params is url.Values type
func Post(apiUrl string, params url.Values, args ...int) (rs []byte, err error) {
out := 1000
if len(args) > 0 {
out = args[0]
}
timeOut := time.Duration(out) * time.Millisecond
c := &http.Client{
Timeout: timeOut,
}
resp, err := c.PostForm(apiUrl, params)
if err != nil {
return nil, err
}
// fmt.Println("http:", resp)
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
// API http api
func API(httpUrl string, paramMap Map, method ...string) (rs []byte, err error) {
param := url.Values{}
for k, v := range paramMap {
param.Set(k, v.(string))
}
apiMethod := "post"
if len(method) > 0 {
apiMethod = method[0]
}
if apiMethod == "get" {
rs, err = Get(httpUrl, param)
return
}
rs, err = Post(httpUrl, param)
return
}
// PostFile post file
func PostFile(filename, targetUrl, upParam string) (string, error) {
bodyBuf := &bytes.Buffer{}
bodyWriter := multipart.NewWriter(bodyBuf)
// uploadfile
fileWriter, err := bodyWriter.CreateFormFile(upParam, filename)
if err != nil {
log.Println("error writing to buffer")
return "", err
}
// openfile
fh, err := os.Open(filename)
if err != nil {
log.Println("error opening file")
return "", err
}
// iocopy
_, err = io.Copy(fileWriter, fh)
if err != nil {
return "", err
}
contentType := bodyWriter.FormDataContentType()
bodyWriter.Close()
resp, err := http.Post(targetUrl, contentType, bodyBuf)
if err != nil {
return "", err
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
log.Println(resp.Status)
// fmt.Println(string(respBody))
return string(respBody), nil
}
var (
Url url.Values = url.Values{}
ajax int64
)
// TestRest test restful and return json
func (router *Engine) TestRest(httpUrl string, param url.Values) {
listUrl := strings.Split(httpUrl, "/")
lastUrl := listUrl[len(listUrl)-1]
url := "/t_" + lastUrl
router.GET(url, func(c *Context) {
data, err := Post(httpUrl, param)
if err != nil {
log.Printf("Request failed, error message:\r\n%v", err)
} else {
var netReturn map[string]interface{}
json.Unmarshal(data, &netReturn)
reContent := netReturn["content"]
c.JSON(200, reContent)
}
})
}
// TestJson test restful and return json
func (router *Engine) TestJson(httpUrl string, param url.Values, args ...string) {
var content string
if len(args) > 0 {
content = args[0]
} else {
// content = "content"
content = "data"
}
listUrl := strings.Split(httpUrl, "/")
lastUrl := listUrl[len(listUrl)-1]
url := "/t/" + lastUrl + "json"
router.GET(url, func(c *Context) {
data, err := Post(httpUrl, param)
if err != nil {
log.Printf("Request failed, error message:\r\n%v", err)
} else {
var netReturn map[string]interface{}
// ffjson.Unmarshal(data, &netReturn)
json.Unmarshal(data, &netReturn)
reContent := netReturn[content]
c.JSON(200, reContent)
}
})
}
// TestHtml test restful and show pretty in the browser
func (router *Engine) TestHtml(httpUrl string, paramMap Map, args ...string) {
if ajax != 1 {
router.StaticFile("/t/ajax", "./views/js/ajax.js")
}
ajax = 1
param := url.Values{}
for k, v := range paramMap {
param.Set(k, v.(string))
}
listUrl := strings.Split(httpUrl, "/")
lastUrl := listUrl[len(listUrl)-1]
url := "/t/" + lastUrl
if len(args) > 0 {
router.TestJson(httpUrl, param, args[0])
} else {
router.TestJson(httpUrl, param)
}
router.GET(url, func(c *Context) {
c.HTML(200, "json.html", Map{
"test": httpUrl,
})
})
}
// TestFile test restful and show pretty in the browser
func (router *Engine) TestFile(httpUrl string, paramMap Map, filename, upParam string) {
if ajax != 1 {
router.StaticFile("/t/ajax", "./views/js/ajax.js")
}
ajax = 1
var (
url string
i int64
)
for k, v := range paramMap {
i++
if i == 1 {
url += k + "=" + v.(string)
} else {
url += "&" + k + "=" + v.(string)
}
}
confUrl := httpUrl + "?" + url
fmt.Println("confUrl-------", confUrl)
// confUrl := url.Values{}
listUrl := strings.Split(httpUrl, "/")
lastUrl := listUrl[len(listUrl)-1]
htmlurl := "/t/" + lastUrl
jsonurl := htmlurl + "json"
router.GET(jsonurl, func(c *Context) {
resp, err := PostFile(filename, confUrl, upParam)
if err != nil {
fmt.Println("err--------", err)
}
fmt.Println("resp---------", resp)
c.JSON(200, resp)
})
router.GET(htmlurl, func(c *Context) {
c.HTML(200, "json.html", Map{
"test": httpUrl,
})
})
}