/
helper.go
67 lines (55 loc) · 1.67 KB
/
helper.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
package servers
import (
"errors"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
uuid "github.com/satori/go.uuid"
"github.com/deepvalue-network/software/libs/hash"
)
func fetchHashFromParams(hashAdapter hash.Adapter, w http.ResponseWriter, r *http.Request, keyname string) *hash.Hash {
vars := mux.Vars(r)
if hashAsStr, ok := vars[keyname]; ok {
hash, err := hashAdapter.FromString(hashAsStr)
if err != nil {
renderBadRequest(w, err, []byte(invalidHashErrorOutput))
return nil
}
return hash
}
output := fmt.Sprintf(missingParamErrorOutput, keyname)
renderBadRequest(w, errors.New(output), []byte(output))
return nil
}
func fetchIDFromParams(w http.ResponseWriter, r *http.Request, keyname string) *uuid.UUID {
vars := mux.Vars(r)
if idAsString, ok := vars[keyname]; ok {
id, err := uuid.FromString(idAsString)
if err != nil {
renderBadRequest(w, err, []byte(invalidIDErrorOutput))
return nil
}
return &id
}
output := fmt.Sprintf(missingParamErrorOutput, keyname)
renderBadRequest(w, errors.New(output), []byte(output))
return nil
}
func renderInsToJSON(w http.ResponseWriter, ins interface{}, err error) {
panic(errors.New("TODO: finish the renderInsToJSON func in the restapi server helper"))
}
func renderSuccess(w http.ResponseWriter, data []byte) {
w.WriteHeader(http.StatusOK)
w.Write(data)
}
func renderError(w http.ResponseWriter, err error, output []byte) {
log.Printf("Error: %s\n", err.Error())
w.WriteHeader(http.StatusInternalServerError)
w.Write(output)
}
func renderBadRequest(w http.ResponseWriter, err error, output []byte) {
log.Printf("BadRequest: %s\n", err.Error())
w.WriteHeader(http.StatusBadRequest)
w.Write(output)
}