forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
68 lines (53 loc) · 1.1 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
package main
import (
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/lxc/lxd/shared"
)
func WriteJSON(w http.ResponseWriter, body interface{}) error {
var output io.Writer
var captured *bytes.Buffer
output = w
if debug {
captured = &bytes.Buffer{}
output = io.MultiWriter(w, captured)
}
err := json.NewEncoder(output).Encode(body)
if captured != nil {
shared.DebugJson(captured)
}
return err
}
func etagHash(data interface{}) (string, error) {
etag := sha256.New()
err := json.NewEncoder(etag).Encode(data)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", etag.Sum(nil)), nil
}
func etagCheck(r *http.Request, data interface{}) error {
match := r.Header.Get("If-Match")
if match == "" {
return nil
}
hash, err := etagHash(data)
if err != nil {
return err
}
if hash != match {
return fmt.Errorf("ETag doesn't match: %s vs %s", hash, match)
}
return nil
}
func loadModule(module string) error {
if shared.PathExists(fmt.Sprintf("/sys/module/%s", module)) {
return nil
}
_, err := shared.RunCommand("modprobe", module)
return err
}