voce/handler/posten.go

121 lines
2.3 KiB
Go
Raw Normal View History

2015-09-24 18:42:56 +02:00
package handler
import (
"encoding/json"
"net/http"
"time"
"github.com/dalu/voce/model"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type PostHandler struct {
MS *mgo.Session
DB string
C string
}
func (h *PostHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
h.GET(w, r)
case "POST":
h.POST(w, r)
case "PUT":
h.PUT(w, r)
case "DELETE":
h.DELETE(w, r)
default:
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
}
}
func (h *PostHandler) GET(w http.ResponseWriter, r *http.Request) {
ms := h.MS.Copy()
defer ms.Close()
c := ms.DB(h.DB).C(h.C)
if !bsonRE.MatchString(r.URL.Path) {
//all
dv := []model.Post{}
if e := c.Find(nil).All(&dv); e != nil {
http.Error(w, e.Error(), 500)
return
}
enc := json.NewEncoder(w)
if e := enc.Encode(dv); e != nil {
http.Error(w, e.Error(), 500)
return
}
} else {
//one
dv := model.Post{}
if e := c.FindId(bson.ObjectIdHex(r.URL.Path)).One(&dv); e != nil {
http.Error(w, e.Error(), 500)
return
}
enc := json.NewEncoder(w)
if e := enc.Encode(dv); e != nil {
http.Error(w, e.Error(), 500)
return
}
}
}
func (h *PostHandler) POST(w http.ResponseWriter, r *http.Request) {
ms := h.MS.Copy()
defer ms.Close()
c := ms.DB(h.DB).C(h.C)
dv := new(model.Post)
dec := json.NewDecoder(r.Body)
if e := dec.Decode(dv); e != nil {
http.Error(w, e.Error(), 400)
return
}
if e := c.UpdateId(dv.Id, dv); e != nil {
http.Error(w, e.Error(), 400)
return
}
w.WriteHeader(200)
}
func (h *PostHandler) PUT(w http.ResponseWriter, r *http.Request) {
ms := h.MS.Copy()
defer ms.Close()
c := ms.DB(h.DB).C(h.C)
dv := new(model.Post)
dec := json.NewDecoder(r.Body)
if e := dec.Decode(dv); e != nil {
http.Error(w, e.Error(), 400)
return
}
dv.Date = time.Now()
if e := c.Insert(dv); e != nil {
http.Error(w, e.Error(), 400)
return
}
w.WriteHeader(201)
}
func (h *PostHandler) DELETE(w http.ResponseWriter, r *http.Request) {
if !bsonRE.MatchString(r.URL.Path) {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
ms := h.MS.Copy()
defer ms.Close()
c := ms.DB(h.DB).C(h.C)
if e := c.RemoveId(bson.ObjectIdHex(r.URL.Path)); e != nil {
http.Error(w, e.Error(), 500)
}
w.WriteHeader(200)
}