-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathutil.go
81 lines (72 loc) · 2 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
81
package avs
import (
"crypto/rand"
"encoding/json"
"fmt"
"io"
"mime"
"mime/multipart"
"net/http"
"net/textproto"
"strings"
)
var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
// UUID holds a 16 byte unique identifier.
type UUID []byte
// String returns a string representation of the UUID.
func (uuid UUID) String() string {
if len(uuid) != 16 {
return ""
}
b := []byte(uuid)
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
}
// NewUUID returns a randomly generated UUID.
func NewUUID() (UUID, error) {
b := make([]byte, 16)
n, err := io.ReadFull(rand.Reader, b)
if n != len(b) || err != nil {
return nil, err
}
b[8] = b[8]&^0xc0 | 0x80
b[6] = b[6]&^0xf0 | 0x40
return UUID(b), nil
}
func RandomUUIDString() string {
uuid, err := NewUUID()
if err != nil {
panic("RandomUUIDString: unable to create UUID")
}
return uuid.String()
}
func newMultipartReaderFromResponse(resp *http.Response) (*multipart.Reader, error) {
// Work around bug in Amazon's downchannel server.
contentType := strings.Replace(resp.Header.Get("Content-Type"), "type=application/json", `type="application/json"`, 1)
mediatype, params, err := mime.ParseMediaType(contentType)
if err != nil {
return nil, err
}
if !strings.HasPrefix(mediatype, "multipart/") {
return nil, fmt.Errorf("unexpected content type %s", mediatype)
}
return multipart.NewReader(resp.Body, params["boundary"]), nil
}
func escapeQuotes(s string) string {
return quoteEscaper.Replace(s)
}
// Encodes a JSON value and writes it to a field with the provided multipart writer.
func writeJSON(writer *multipart.Writer, fieldname string, value interface{}) error {
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"`, escapeQuotes(fieldname)))
h.Set("Content-Type", "application/json; charset=UTF-8")
p, err := writer.CreatePart(h)
if err != nil {
return err
}
data, err := json.Marshal(value)
if err != nil {
return err
}
_, err = p.Write(data)
return err
}