added REST API and simple unit test - and compose starter, still WIP for integ test
This commit is contained in:
43
api/api.go
Normal file
43
api/api.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/go-chi/chi/middleware"
|
||||
"github.com/go-chi/render"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
func ApiInit() {
|
||||
log.Println("Initializing API server")
|
||||
r := chi.NewRouter()
|
||||
addMiddleware(r)
|
||||
addRoutes(r)
|
||||
start(r)
|
||||
}
|
||||
|
||||
func addMiddleware(mux *chi.Mux) {
|
||||
mux.Use(middleware.RequestID)
|
||||
mux.Use(middleware.Logger)
|
||||
mux.Use(middleware.Recoverer)
|
||||
mux.Use(middleware.URLFormat)
|
||||
mux.Use(render.SetContentType(render.ContentTypeJSON))
|
||||
mux.Use(middleware.Timeout(60 * time.Second)) // Set a timeout
|
||||
}
|
||||
|
||||
func addRoutes(mux *chi.Mux) {
|
||||
// Add a simple resource
|
||||
mux.Mount("/app", AppResource{}.Routes())
|
||||
// Live a healthy life!
|
||||
mux.Get("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte("yolo"))
|
||||
})
|
||||
}
|
||||
|
||||
func start(mux *chi.Mux) {
|
||||
err := http.ListenAndServe(":8080", mux)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
71
api/api_test.go
Normal file
71
api/api_test.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/go-chi/chi"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGetRoute(t *testing.T) {
|
||||
r := chi.NewRouter()
|
||||
addRoutes(r)
|
||||
ts := httptest.NewServer(r)
|
||||
defer ts.Close()
|
||||
rx := Response{}
|
||||
_, resp := testRequest(t, ts, "GET", "/app/1", nil)
|
||||
err := json.Unmarshal([]byte(resp), &rx)
|
||||
if err != nil {
|
||||
t.Fatalf("Response incorrect form ", resp)
|
||||
}
|
||||
if !reflect.DeepEqual(Response{Operation: "GET", Identifier: 1}, rx) {
|
||||
t.Fatalf("Response not equal expected values ", resp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostRoute(t *testing.T) {
|
||||
r := chi.NewRouter()
|
||||
addRoutes(r)
|
||||
ts := httptest.NewServer(r)
|
||||
defer ts.Close()
|
||||
rx := Response{}
|
||||
_, resp := testRequest(t, ts, "POST", "/app/1", nil)
|
||||
err := json.Unmarshal([]byte(resp), &rx)
|
||||
if err != nil {
|
||||
t.Fatalf("Response incorrect form ", resp)
|
||||
}
|
||||
if !reflect.DeepEqual(Response{Operation: "POST", Identifier: 1}, rx) {
|
||||
t.Fatalf("Response not equal expected values ", resp)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//----------------------------------------------------------------------------
|
||||
// HELPER METHOD
|
||||
//----------------------------------------------------------------------------
|
||||
func testRequest(t *testing.T, ts *httptest.Server, method, path string, body io.Reader) (int, string) {
|
||||
req, err := http.NewRequest(method, ts.URL+path, body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return 0, ""
|
||||
}
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return resp.StatusCode, ""
|
||||
}
|
||||
|
||||
respBody, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return resp.StatusCode, ""
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
return resp.StatusCode, string(respBody)
|
||||
}
|
||||
84
api/app.go
Normal file
84
api/app.go
Normal file
@@ -0,0 +1,84 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
. "drone-with-go/model"
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/go-chi/render"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type AppResource struct{}
|
||||
|
||||
// Routes creates a REST router for the todos resource
|
||||
func (self AppResource) Routes() chi.Router {
|
||||
r := chi.NewRouter()
|
||||
|
||||
r.Route("/{id}", func(r chi.Router) {
|
||||
r.Use(AppCtx) // do some preprocessing of the input value
|
||||
r.Get("/", self.remember)
|
||||
r.Post("/", self.memorize)
|
||||
})
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
func (self AppResource) remember(w http.ResponseWriter, r *http.Request) {
|
||||
record := r.Context().Value("record").(*Record)
|
||||
render.Status(r, http.StatusOK)
|
||||
render.Render(w, r, NewResponse("GET", record.Value))
|
||||
}
|
||||
|
||||
func (self AppResource) memorize(w http.ResponseWriter, r *http.Request) {
|
||||
record := r.Context().Value("record").(*Record)
|
||||
render.Status(r, http.StatusOK)
|
||||
render.Render(w, r, NewResponse("POST", record.Value))
|
||||
}
|
||||
|
||||
// AppCtx middleware is used to load an object from
|
||||
// the URL parameters passed through as the request. In case
|
||||
// the object could not be found, we stop here and return a 404.
|
||||
func AppCtx(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var record *Record
|
||||
|
||||
if id := chi.URLParam(r, "id"); id != "" {
|
||||
i64, err := strconv.ParseUint(id, 10, 32)
|
||||
if err != nil {
|
||||
render.Render(w, r, ErrNotANumber)
|
||||
return
|
||||
}
|
||||
// Here is where we could lookup the record...
|
||||
record = &Record{Value: i64}
|
||||
|
||||
} else {
|
||||
render.Render(w, r, ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), "record", record)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// response renderers
|
||||
//--------------------------------------------------------------------------
|
||||
type Response struct {
|
||||
Operation string `json:"op"`
|
||||
Identifier uint64 `json:"id"`
|
||||
}
|
||||
|
||||
func (u *Response) Bind(r *http.Request) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *Response) Render(w http.ResponseWriter, r *http.Request) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewResponse(action string, id uint64) *Response {
|
||||
resp := &Response{Operation: action, Identifier: id}
|
||||
return resp
|
||||
}
|
||||
50
api/error.go
Normal file
50
api/error.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"github.com/go-chi/render"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Error response payloads & renderers
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
// ErrResponse renderer type for handling all sorts of errors.
|
||||
//
|
||||
// In the best case scenario, the excellent github.com/pkg/errors package
|
||||
// helps reveal information on the error, setting it on Err, and in the Render()
|
||||
// method, using it to set the application-specific error code in AppCode.
|
||||
type ErrResponse struct {
|
||||
Err error `json:"-"` // low-level runtime error
|
||||
HTTPStatusCode int `json:"-"` // http response status code
|
||||
|
||||
StatusText string `json:"status"` // user-level status message
|
||||
AppCode int64 `json:"code,omitempty"` // application-specific error code
|
||||
ErrorText string `json:"error,omitempty"` // application-level error message, for debugging
|
||||
}
|
||||
|
||||
func (e *ErrResponse) Render(w http.ResponseWriter, r *http.Request) error {
|
||||
render.Status(r, e.HTTPStatusCode)
|
||||
return nil
|
||||
}
|
||||
|
||||
func ErrInvalidRequest(err error) render.Renderer {
|
||||
return &ErrResponse{
|
||||
Err: err,
|
||||
HTTPStatusCode: 400,
|
||||
StatusText: "Invalid request.",
|
||||
ErrorText: err.Error(),
|
||||
}
|
||||
}
|
||||
|
||||
func ErrRender(err error) render.Renderer {
|
||||
return &ErrResponse{
|
||||
Err: err,
|
||||
HTTPStatusCode: 422,
|
||||
StatusText: "Error rendering response.",
|
||||
ErrorText: err.Error(),
|
||||
}
|
||||
}
|
||||
|
||||
var ErrNotFound = &ErrResponse{HTTPStatusCode: 404, StatusText: "Resource not found."}
|
||||
var ErrNotANumber = &ErrResponse{HTTPStatusCode: 400, StatusText: "Value not a number."}
|
||||
Reference in New Issue
Block a user