forked from eatmoreapple/openwechat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
78 lines (70 loc) · 1.48 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
package openwechat
import (
"bytes"
"encoding/json"
"io"
"math/rand"
"net/http"
"path/filepath"
"reflect"
"strconv"
"strings"
"time"
"unsafe"
)
func jsonEncode(v interface{}) (io.Reader, error) {
var buffer = bytes.NewBuffer(nil)
encoder := json.NewEncoder(buffer)
// 这里要设置禁止html转义
encoder.SetEscapeHTML(false)
if err := encoder.Encode(v); err != nil {
return nil, err
}
return buffer, nil
}
// 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()
}
// GetFileContentType 获取文件上传的类型
func GetFileContentType(file io.Reader) (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 stringToByte(s string) []byte {
return *(*[]byte)(unsafe.Pointer(&*(*reflect.StringHeader)(unsafe.Pointer(&s))))
}