forked from TheThingsArchive/jolie
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.go
More file actions
104 lines (93 loc) · 2.01 KB
/
api.go
File metadata and controls
104 lines (93 loc) · 2.01 KB
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
101
102
103
104
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"net/http"
)
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
var routes = Routes{
Route{
"Index",
"GET",
"/",
IndexHandler,
},
Route{
"ApplicationsIndex",
"GET",
"/applications",
ApplicationsIndexHandler,
},
Route{
"ApplicationsCreate",
"POST",
"/applications",
ApplicationsCreateHandler,
},
Route{
"DevicesIndex",
"GET",
"/devices",
DevicesIndexHandler,
},
}
func JSONResponse(status int, data interface{}, w http.ResponseWriter) {
b, err := json.Marshal(data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
} else {
w.WriteHeader(status)
w.Header().Set("Content-Type", "application/json")
w.Write(b)
}
}
func IndexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Welcome to The Jolie API")
}
func ApplicationsIndexHandler(w http.ResponseWriter, r *http.Request) {
apps, err := database.GetApplications()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
JSONResponse(http.StatusOK, apps, w)
}
func ApplicationsCreateHandler(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
app := new(Application)
err := decoder.Decode(&app)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Insert Datas
err = database.SaveApplication(app)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
JSONResponse(http.StatusCreated, app, w)
}
func DevicesIndexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Listing Devices registered with the things network")
}
func Api() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
var handler http.Handler
handler = route.HandlerFunc
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
}
return router
}