forked from eatmoreapple/openwechat
-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.go
95 lines (84 loc) · 1.84 KB
/
parser.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
package openwechat
import (
"bytes"
"encoding/json"
"encoding/xml"
"io"
"math/rand"
"mime/multipart"
"net/http"
"path/filepath"
"reflect"
"strconv"
"strings"
"time"
"unsafe"
)
func ToBuffer(v interface{}) (*bytes.Buffer, error) {
var buffer bytes.Buffer
encoder := json.NewEncoder(&buffer)
// 这里要设置禁止html转义
encoder.SetEscapeHTML(false)
err := encoder.Encode(v)
return &buffer, err
}
// GetRandomDeviceId 获取随机设备id
func GetRandomDeviceId() string {
rand.Seed(time.Now().Unix())
var builder strings.Builder
builder.Grow(16)
builder.WriteString("e")
for i := 0; i < 15; i++ {
r := rand.Intn(9)
builder.WriteString(strconv.Itoa(r))
}
return builder.String()
}
func getWebWxDataTicket(cookies []*http.Cookie) string {
for _, cookie := range cookies {
if cookie.Name == "webwx_data_ticket" {
return cookie.Value
}
}
return ""
}
// GetFileContentType 获取文件上传的类型
func GetFileContentType(file multipart.File) (string, error) {
data := make([]byte, 512)
if _, err := file.Read(data); err != nil {
return "", err
}
return http.DetectContentType(data), nil
}
func getFileExt(name string) string {
ext := filepath.Ext(name)
if len(ext) == 0 {
ext = "undefined"
}
return strings.TrimPrefix(ext, ".")
}
const (
pic = "pic"
video = "video"
doc = "doc"
)
// 微信匹配文件类型策略
func getMessageType(filename string) string {
ext := getFileExt(filename)
if _, ok := imageType[ext]; ok {
return pic
}
if ext == videoType {
return video
}
return doc
}
func scanXml(reader io.Reader, v interface{}) error {
return xml.NewDecoder(reader).Decode(v)
}
func scanJson(reader io.Reader, v interface{}) error {
return json.NewDecoder(reader).Decode(v)
}
func stringToByte(s string) []byte {
return *(*[]byte)(unsafe.Pointer(&*(*reflect.StringHeader)(unsafe.Pointer(&s))))
}