-
Notifications
You must be signed in to change notification settings - Fork 70
/
request.go
88 lines (83 loc) · 1.88 KB
/
request.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
package weixinmp
import (
"crypto/sha1"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
"sort"
"strings"
)
// request from weixinmp
type Request struct {
Token string
// request common fields
ToUserName string
FromUserName string
CreateTime int64
MsgType string
// message request fields
Content string
MsgId int64
PicUrl string
MediaId string
Format string
ThumbMediaId string
LocationX float64 `xml:"Location_X"`
LocationY float64 `xml:"Location_Y"`
Scale float64
Label string
Title string
Description string
Url string
Recognition string
// event request fields
Event string
EventKey string
Ticket string
Latitude float64
Longitude float64
Precision float64
}
// validate request
func (this *Request) IsValid(rw http.ResponseWriter, req *http.Request) bool {
if !this.checkSignature(req) {
rw.WriteHeader(http.StatusUnauthorized)
rw.Write([]byte(http.StatusText(http.StatusUnauthorized)))
return false
}
if req.Method != "POST" {
rw.WriteHeader(http.StatusOK)
rw.Write([]byte(req.FormValue("echostr")))
return false
}
if err := this.parseRequest(req); err != nil {
rw.WriteHeader(http.StatusBadRequest)
rw.Write([]byte(err.Error()))
return false
}
return true
}
func (this *Request) parseRequest(req *http.Request) error {
raw, err := ioutil.ReadAll(req.Body)
if err != nil {
return err
}
defer req.Body.Close()
if err := xml.Unmarshal(raw, this); err != nil {
return err
}
return nil
}
func (this *Request) checkSignature(req *http.Request) bool {
ss := sort.StringSlice{
this.Token,
req.FormValue("timestamp"),
req.FormValue("nonce"),
}
sort.Strings(ss) // sort strings by dictionary
s := strings.Join(ss, "") // concatenate strings
h := sha1.New()
h.Write([]byte(s))
return fmt.Sprintf("%x", h.Sum(nil)) == req.FormValue("signature")
}