-
Notifications
You must be signed in to change notification settings - Fork 0
/
ajax.go
82 lines (67 loc) · 1.36 KB
/
ajax.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
package ajax
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"syscall/js"
)
// Ajax represents a JQuery Ajax method.
type Ajax struct {
URL string
Method string
Data []byte
Done AjaxDone
Fail AjaxFail
}
// Response contains the data retrieved
// from the query above.
type Response struct {
Rows js.Value `json:"rows"`
Total js.Value `json:"total"`
}
type AjaxDone func(data js.Value)
type AjaxFail func(jqXHR js.Value)
func (ajax Ajax) Send() {
go func() {
var (
err error
data []byte
reqURL *url.URL
res *http.Response
)
if reqURL, err = url.Parse(ajax.URL); err != nil {
fmt.Println(err)
return
}
req := &http.Request{
Method: ajax.Method,
URL: reqURL,
Header: map[string][]string{
"Content-Type": {"application/json; charset=UTF-8"},
},
}
if len(ajax.Data) > 0 {
req.Body = ioutil.NopCloser(strings.NewReader(string(ajax.Data)))
}
if res, err = http.DefaultClient.Do(req); err != nil {
fmt.Println(err)
return
}
if data, err = ioutil.ReadAll(res.Body); err != nil {
fmt.Println(err)
return
}
res.Body.Close()
//jsResponse := js.Global().Get("JSON").Call("stringify", string(data))
jsResponse := js.ValueOf(string(data))
if res.StatusCode == 200 {
ajax.Done(jsResponse)
} else {
if ajax.Fail != nil {
ajax.Fail(jsResponse)
}
}
}()
}