-
Notifications
You must be signed in to change notification settings - Fork 12
/
main_rest.go
76 lines (63 loc) · 1.38 KB
/
main_rest.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
package main
import (
"encoding/json"
"errors"
"log"
"net/http"
"github.com/husobee/vestigo"
)
func mainREST(addr string) {
r := vestigo.NewRouter()
r.Post("/info", SetInfo)
log.Fatal(http.ListenAndServeTLS(addr, certFile, keyFile, r))
}
// SetInfo - Rest HTTP Handler
func SetInfo(w http.ResponseWriter, r *http.Request) {
var (
input apiInput
response apiResponse
)
// decode input
decoder := json.NewDecoder(r.Body)
decoder.Decode(&input)
r.Body.Close()
// validate input
if err := validate(input); err != nil {
response.Success = false
response.Reason = err.Error()
respBytes, _ := json.Marshal(response)
w.WriteHeader(400)
w.Write(respBytes)
return
}
response.Success = true
respBytes, _ := json.Marshal(response)
w.WriteHeader(200)
w.Write(respBytes)
}
type apiResponse struct {
Success bool `json:"success"`
Reason string `json:"reason,omitempty"`
}
type apiInput struct {
Name string `json:"name"`
Age int `json:"int"`
Height int `json:"height"`
}
// Validate - implementation of Validatable
func (ai apiInput) Validate() error {
var err validationErrors
if ai.Name == "" {
err = append(err, errors.New("Name must be present"))
}
if ai.Age <= 0 {
err = append(err, errors.New("Age must be real"))
}
if ai.Height <= 0 {
err = append(err, errors.New("Height must be real"))
}
if len(err) == 0 {
return nil
}
return err
}