API endpoints.
This commit is contained in:
parent
1e283e7cd6
commit
e1685bd32b
8 changed files with 129 additions and 11 deletions
|
@ -1,7 +0,0 @@
|
|||
package api
|
||||
|
||||
import "github.com/gorilla/mux"
|
||||
|
||||
func Handler() *mux.Router {
|
||||
return mux.NewRouter()
|
||||
}
|
35
api/handler.go
Normal file
35
api/handler.go
Normal file
|
@ -0,0 +1,35 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/gorilla/schema"
|
||||
"github.com/thermokarst/bactdb/datastore"
|
||||
"github.com/thermokarst/bactdb/router"
|
||||
)
|
||||
|
||||
var (
|
||||
store = datastore.NewDatastore(nil)
|
||||
schemaDecoder = schema.NewDecoder()
|
||||
)
|
||||
|
||||
func Handler() *mux.Router {
|
||||
m := router.API()
|
||||
m.Get(router.User).Handler(handler(serveUser))
|
||||
m.Get(router.Users).Handler(handler(serveUsers))
|
||||
return m
|
||||
}
|
||||
|
||||
type handler func(http.ResponseWriter, *http.Request) error
|
||||
|
||||
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
err := h(w, r)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
fmt.Fprintf(w, "error: %s", err)
|
||||
log.Println(err)
|
||||
}
|
||||
}
|
19
api/helpers.go
Normal file
19
api/helpers.go
Normal file
|
@ -0,0 +1,19 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// writeJSON writes a JSON Content-Type header and a JSON-encoded object to
|
||||
// the http.ResponseWriter.
|
||||
func writeJSON(w http.ResponseWriter, v interface{}) error {
|
||||
data, err := json.MarshalIndent(v, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.Header().Set("content-type", "application/json; charset=utf-8")
|
||||
_, err = w.Write(data)
|
||||
return err
|
||||
}
|
42
api/users.go
Normal file
42
api/users.go
Normal file
|
@ -0,0 +1,42 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
|
||||
"net/http"
|
||||
|
||||
"github.com/thermokarst/bactdb/models"
|
||||
)
|
||||
|
||||
func serveUser(w http.ResponseWriter, r *http.Request) error {
|
||||
id, err := strconv.ParseInt(mux.Vars(r)["ID"], 10, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
user, err := store.Users.Get(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return writeJSON(w, user)
|
||||
}
|
||||
|
||||
func serveUsers(w http.ResponseWriter, r *http.Request) error {
|
||||
var opt models.UserListOptions
|
||||
if err := schemaDecoder.Decode(&opt, r.URL.Query()); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
users, err := store.Users.List(&opt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if users == nil {
|
||||
users = []*models.User{}
|
||||
}
|
||||
|
||||
return writeJSON(w, users)
|
||||
}
|
Reference in a new issue