-
Notifications
You must be signed in to change notification settings - Fork 0
/
pcpMid.go
82 lines (68 loc) · 1.79 KB
/
pcpMid.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 gopcp_service
import (
"bytes"
"encoding/json"
"errors"
"github.com/lock-free/gopcp"
"net/http"
"net/url"
)
type PcpHttpResponse struct {
Data interface{} `json:"text"`
Errno int `json:"errno"`
ErrMsg string `json:"errMsg"`
}
func JSONMarshal(t interface{}) ([]byte, error) {
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
err := encoder.Encode(t)
return buffer.Bytes(), err
}
func ResponseToBytes(pcpHttpRes PcpHttpResponse) []byte {
bytes, jerr := JSONMarshal(pcpHttpRes)
if jerr != nil {
ret, _ := json.Marshal(ErrorToResponse(jerr, 530))
return ret
} else {
return bytes
}
}
type MidFunType = func(http.ResponseWriter, *http.Request, interface{}) (interface{}, error)
func ErrorToResponse(err error, code int) PcpHttpResponse {
return PcpHttpResponse{nil, code, err.Error()}
}
func GetPcpMid(sandbox *gopcp.Sandbox) MidFunType {
pcpServer := gopcp.NewPcpServer(sandbox)
return func(w http.ResponseWriter, r *http.Request, attachment interface{}) (interface{}, error) {
var pcpHttpRes PcpHttpResponse
var arr interface{}
var err error = nil
var rawQuery string
var ret interface{}
if r.Method == "GET" {
rawQuery, err = url.QueryUnescape(r.URL.RawQuery)
if err == nil {
// parse url query
err = json.Unmarshal([]byte(rawQuery), &arr)
}
} else if r.Method == "POST" {
// get post body
arr, err = GetJsonBody(r)
} else {
err = errors.New("Unsupported method")
}
if err != nil {
pcpHttpRes = ErrorToResponse(err, 530)
} else {
ret, err = pcpServer.ExecuteJsonObj(arr, attachment)
if err != nil {
pcpHttpRes = ErrorToResponse(err, 530)
} else {
pcpHttpRes = PcpHttpResponse{ret, 0, ""}
}
}
w.Write(ResponseToBytes(pcpHttpRes))
return arr, err
}
}