-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
80 lines (73 loc) · 1.61 KB
/
util.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
package restgo
import (
"context"
"go.uber.org/zap/buffer"
"go.uber.org/zap/zapcore"
"net/http"
"net/url"
"os"
)
var (
DefaultClient = New()
)
// The algorithm uses at most sniffLen bytes to make its decision.
const sniffLen = 512
// ZapJSONMarshal Zap JSON 序列化
func ZapJSONMarshal(obj zapcore.ObjectMarshaler) ([]byte, error) {
var entry = zapcore.Entry{}
var fields []zapcore.Field
var enc = zapcore.NewJSONEncoder(zapcore.EncoderConfig{})
var err = obj.MarshalLogObject(enc)
if err != nil {
return nil, err
}
var buf *buffer.Buffer
buf, err = enc.EncodeEntry(entry, fields)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// DetectContentTypeAndSize 发现文件的ContentType和大小
func DetectContentTypeAndSize(filePath string) (string, int64, error) {
var fi, err = os.Stat(filePath)
if err != nil {
return "", 0, err
}
var f *os.File
f, err = os.Open(filePath)
if err != nil {
return "", 0, err
}
defer f.Close()
var buff = make([]byte, sniffLen)
_, err = f.Read(buff)
if err != nil {
return "", 0, err
}
return http.DetectContentType(buff), fi.Size(), nil
}
func CloneURL(o *url.URL) *url.URL {
if o == nil {
return nil
}
return &url.URL{
Scheme: o.Scheme,
Opaque: o.Opaque,
User: o.User,
Host: o.Host,
Path: o.Path,
RawPath: o.RawPath,
ForceQuery: o.ForceQuery,
RawQuery: o.RawQuery,
Fragment: o.Fragment,
RawFragment: o.RawFragment,
}
}
func Download(ctx context.Context, url string) ([]byte, error) {
var rsp, err = DefaultClient.Get(ctx, url)
if err != nil {
return nil, err
}
return rsp.Data()
}