summaryrefslogtreecommitdiff
path: root/jsonrest.go
diff options
context:
space:
mode:
authorNikolaus Gotsche <n@softwarefools.com>2017-09-24 22:51:36 +0200
committerNikolaus Gotsche <n@softwarefools.com>2017-09-24 22:51:36 +0200
commit7e33d4d446d6b7d9a136290993363f833fc13908 (patch)
treedd7ee817baecdbf7105862a3e1ce5277020323b4 /jsonrest.go
First Commit of Project Hexfool
getuuid - Demonstration how linux's uuidgen can be used in go jsonrest - api for restful json usage signup - login on top of an mysql db
Diffstat (limited to 'jsonrest.go')
-rw-r--r--jsonrest.go96
1 files changed, 96 insertions, 0 deletions
diff --git a/jsonrest.go b/jsonrest.go
new file mode 100644
index 0000000..e6e948e
--- /dev/null
+++ b/jsonrest.go
@@ -0,0 +1,96 @@
+package main
+
+import (
+ "net/http"
+ "log"
+ "sync"
+ "github.com/ant0ine/go-json-rest/rest"
+)
+
+func main() {
+ api := rest.NewApi()
+ api.Use(rest.DefaultDevStack...)
+// api.SetApp(rest.AppSimple(func(w rest.ResponseWriter, r *rest.Request) {
+// w.WriteJson(map[string]string{"Body": "Hello World!"})
+// }))
+// log.Fatal(http.ListenAndServe(":8086", api.MakeHandler()))
+ router, err := rest.MakeRouter(
+ rest.Get("/countries", GetAllCountries),
+ rest.Post("/countries", PostCountry),
+ rest.Get("/countries/:code", GetCountry),
+ rest.Delete("/countries/:code", DeleteCountry),
+ )
+ if err != nil{
+ log.Fatal(err)
+ }
+ api.SetApp(router)
+ log.Fatal(http.ListenAndServe(":8086", api.MakeHandler()))
+}
+
+type Country struct {
+ Code string
+ Name string
+}
+
+var store = map[string]*Country{}
+
+var lock = sync.RWMutex{}
+
+func GetCountry(w rest.ResponseWriter, r *rest.Request) {
+ code := r.PathParam("code")
+
+ lock.RLock()
+ var country *Country
+ if store[code] != nil {
+ country = &Country{}
+ *country = *store[code]
+ }
+ lock.RUnlock()
+ if country == nil {
+ rest.NotFound(w, r)
+ return
+ }
+ w.WriteJson(country)
+
+}
+
+func GetAllCountries(w rest.ResponseWriter, r *rest.Request) {
+ lock.RLock()
+ countries := make([]Country, len(store))
+ i := 0
+ for _, country := range store {
+ countries[i] = *country
+ i++
+ }
+ lock.RUnlock()
+ w.WriteJson(&countries)
+}
+
+func PostCountry(w rest.ResponseWriter, r *rest.Request) {
+ country := Country{}
+ err := r.DecodeJsonPayload(&country)
+ if err != nil {
+ rest.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ if country.Code == "" {
+ rest.Error(w, "country code required", 400)
+ return
+ }
+ if country.Name == "" {
+ rest.Error(w, "country name required", 400)
+ return
+ }
+ lock.Lock()
+ store[country.Code] = &country
+ lock.Unlock()
+ w.WriteJson(&country)
+}
+
+func DeleteCountry(w rest.ResponseWriter, r *rest.Request) {
+ code := r.PathParam("code")
+ lock.Lock()
+ delete(store, code)
+ lock.Unlock()
+ w.WriteHeader(http.StatusOK)
+}