forked from vadv/gopher-lua-libs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
body.go
58 lines (51 loc) · 1.26 KB
/
body.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
package chef
import (
"bytes"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"io"
"log"
"net/http"
)
// luaBody wraps io.Reader and adds methods for calculating hashes and detecting content
type luaBody struct {
io.Reader
}
// contentType returns the content-type string of luaBody as detected by http.DetectContentType()
func (body *luaBody) contentType() string {
if json.Unmarshal(body.buffer().Bytes(), &struct{}{}) == nil {
return "application/json"
}
return http.DetectContentType(body.buffer().Bytes())
}
// hash calculates the body content hash
func (body *luaBody) hash() (h string) {
b := body.buffer()
// empty buffs should return a empty string
if b.Len() == 0 {
h = hashStr("")
}
h = hashStr(b.String())
return
}
// hashStr returns the base64 encoded SHA1 sum of the toHash string
func hashStr(toHash string) string {
h := sha1.New()
io.WriteString(h, toHash)
hashed := base64.StdEncoding.EncodeToString(h.Sum(nil))
return hashed
}
// buffer creates a byte.buffer copy from a io.Reader resets read on reader to 0,0
func (body *luaBody) buffer() *bytes.Buffer {
var b bytes.Buffer
if body.Reader == nil {
return &b
}
b.ReadFrom(body.Reader)
_, err := body.Reader.(io.Seeker).Seek(0, 0)
if err != nil {
log.Fatal(err)
}
return &b
}