-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
100 lines (78 loc) · 2.3 KB
/
main.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"github.com/gocraft/web"
"github.com/xeipuuv/gojsonschema"
)
type Context struct {
schemaDir string
}
var schemaDir string
func main() {
schemaDir = getSchemaDir()
router := web.New(Context{}).
Middleware(web.LoggerMiddleware). // Use some included middleware
Middleware(web.ShowErrorsMiddleware). // ...
Middleware(web.StaticMiddleware("www")).
Post("/api/v0/keys", (*Context).createKeyValue)
http.ListenAndServe("localhost:8080", router)
}
// ===============================================
// HELPER FUNCTIONS
// ===============================================
// getSchemaDir gets a full file path to the schemas directory
func getSchemaDir() string {
fpdir := filepath.Dir(os.Args[0])
dir, err := filepath.Abs(fpdir)
if err != nil {
println("Couldn't get absolute path of $PWD: " + fpdir)
println("Exiting service.")
panic(err)
}
return filepath.Join(dir, "www/schemas")
}
// validateRequestData takes in a schema path and the request
// and will do the legwork of determining if the post data is valid
func validateRequestData(schemaPath string, r *web.Request) (
document map[string]interface{},
result *gojsonschema.Result,
err error,
) {
err = json.NewDecoder(r.Body).Decode(&document)
if err == nil && schemaPath != "" {
schemaLoader := gojsonschema.NewReferenceLoader(schemaPath)
documentLoader := gojsonschema.NewGoLoader(document)
result, err = gojsonschema.Validate(schemaLoader, documentLoader)
}
return document, result, err
}
// ===============================================
// HANDLERS
// ===============================================
// creatKeyValue creates a new book in the collection
func (c *Context) createKeyValue(w web.ResponseWriter, r *web.Request) {
document, result, err := validateRequestData(
"file://"+schemaDir+"/keyvalue.post.body.json",
r,
)
// lazy output & not setting headers
if err != nil || !result.Valid() {
w.Header()
fmt.Fprintf(w, "The document is not valid. see errors :\n")
if result != nil {
for _, desc := range result.Errors() {
fmt.Fprintf(w, "- %s\n", desc)
}
} else {
fmt.Fprint(w, "The document wasn't valid JSON.")
}
return
}
fmt.Fprint(w, "success", "\n")
fmt.Fprint(w, document, "\n")
fmt.Fprint(w, result, "\n")
}