Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lib.NewRequestHandler removes boilerplate from api package #1682

Merged
merged 2 commits into from
Mar 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 15 additions & 69 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,13 @@
package api

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"time"

"github.com/gorilla/mux"
"github.com/gorilla/schema"
golog "github.com/ipfs/go-log"
apiutil "github.com/qri-io/qri/api/util"
"github.com/qri-io/qri/auth/token"
Expand All @@ -31,7 +27,6 @@ const (
DefaultTemplateHash = "/ipfs/QmeqeRTf2Cvkqdx4xUdWi1nJB2TgCyxmemsL3H4f1eTBaw"
// TemplateUpdateAddress is the URI for the template update
TemplateUpdateAddress = "/ipns/defaulttmpl.qri.io"
jsonContentType = "application/json"
)

func init() {
Expand Down Expand Up @@ -157,6 +152,18 @@ func handleRefRoute(m *mux.Router, ae lib.APIEndpoint, f http.HandlerFunc) {
m.Handle(fmt.Sprintf("%s/%s", ae, "{peername}/{name}/at/{fs}/{hash}/{selector}"), f)
}

// TODO(b5): this is a band-aid that lets us punt on teaching lib about how to
// switch on HTTP verbs. I think we should use tricks like this that leverage
// the gorilla/mux package until we get a better sense of how our API uses
// HTTP verbs
func handleRefRouteMethods(m *mux.Router, ae lib.APIEndpoint, f http.HandlerFunc, methods ...string) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

m.Handle(ae.String(), f).Methods(methods...)
m.Handle(fmt.Sprintf("%s/%s", ae, "{peername}/{name}"), f).Methods(methods...)
m.Handle(fmt.Sprintf("%s/%s", ae, "{peername}/{name}/{selector}"), f).Methods(methods...)
m.Handle(fmt.Sprintf("%s/%s", ae, "{peername}/{name}/at/{fs}/{hash}"), f).Methods(methods...)
m.Handle(fmt.Sprintf("%s/%s", ae, "{peername}/{name}/at/{fs}/{hash}/{selector}"), f).Methods(methods...)
}

// NewServerRoutes returns a Muxer that has all API routes
func NewServerRoutes(s Server) *mux.Router {
cfg := s.Config()
Expand All @@ -165,6 +172,8 @@ func NewServerRoutes(s Server) *mux.Router {
if m == nil {
m = mux.NewRouter()
}
m.Use(refStringMiddleware)
m.Use(token.OAuthTokenMiddleware)

m.Handle(lib.AEHome.String(), s.NoLogMiddleware(s.HomeHandler))
m.Handle(lib.AEHealth.String(), s.NoLogMiddleware(HealthCheckHandler))
Expand Down Expand Up @@ -213,7 +222,7 @@ func NewServerRoutes(s Server) *mux.Router {
m.Handle(lib.AEPreview.String(), s.Middleware(remClientH.DatasetPreviewHandler))

fsih := NewFSIHandlers(s.Instance, cfg.API.ReadOnly)
m.Handle(lib.AEStatus.String(), s.Middleware(fsih.StatusHandler(lib.AEStatus.NoTrailingSlash())))
handleRefRouteMethods(m, lib.AEStatus, s.Middleware(lib.NewHTTPRequestHandler(s.Instance, "fsi.status")), http.MethodGet, http.MethodPost)
m.Handle(lib.AEWhatChanged.String(), s.Middleware(fsih.WhatChangedHandler(lib.AEWhatChanged.NoTrailingSlash())))
m.Handle(lib.AEInit.String(), s.Middleware(fsih.InitHandler(lib.AEInit.NoTrailingSlash())))
m.Handle(lib.AECanInitDatasetWorkDir.String(), s.Middleware(fsih.CanInitDatasetWorkDirHandler(lib.AECanInitDatasetWorkDir.NoTrailingSlash())))
Expand Down Expand Up @@ -250,68 +259,5 @@ func NewServerRoutes(s Server) *mux.Router {
m.Handle(lib.AEWebUI.String(), s.Middleware(WebuiHandler))
}

m.Use(refStringMiddleware)
m.Use(token.OAuthTokenMiddleware)

return m
}

// snoop reads from an io.ReadCloser and restores it so it can be read again
func snoop(body *io.ReadCloser) (io.ReadCloser, error) {
if body != nil && *body != nil {
result, err := ioutil.ReadAll(*body)
(*body).Close()

if err != nil {
return nil, err
}
if len(result) == 0 {
return nil, io.EOF
}

*body = ioutil.NopCloser(bytes.NewReader(result))
return ioutil.NopCloser(bytes.NewReader(result)), nil
}
return nil, io.EOF
}

var decoder = schema.NewDecoder()

// UnmarshalParams deserialzes a lib req params stuct pointer from an HTTP
// request
func UnmarshalParams(r *http.Request, p interface{}) error {
// TODO(arqu): once APIs have a strict mapping to Params this line
// should be removed and should error out on unknown keys
decoder.IgnoreUnknownKeys(true)
defer func() {
if defSetter, ok := p.(lib.NZDefaultSetter); ok {
defSetter.SetNonZeroDefaults()
}
}()

if r.Method == http.MethodPost || r.Method == http.MethodPut {

if r.Header.Get("Content-Type") == jsonContentType {
body, err := snoop(&r.Body)
if err != nil && err != io.EOF {
return err
}
// this avoids resolving on empty body requests
// and tries to handle it almost like a GET
if err != io.EOF {
if err := json.NewDecoder(body).Decode(p); err != nil {
return err
}
}
}
}

if ru, ok := p.(lib.RequestUnmarshaller); ok {
return ru.UnmarshalFromRequest(r)
}

if err := r.ParseForm(); err != nil {
return err
}
return decoder.Decode(p, r.Form)
}
1 change: 0 additions & 1 deletion api/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,6 @@ func TestServerReadOnlyRoutes(t *testing.T) {
{"POST", "/registry/profile/new", 403},
{"POST", "/registry/profile/prove", 403},
{"GET", "/checkout/", 403},
{"GET", "/status/", 403},
{"GET", "/init/", 403},

// active endpoints:
Expand Down
24 changes: 12 additions & 12 deletions api/datasets.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ func extensionToMimeType(ext string) string {

func (h *DatasetHandlers) listHandler(w http.ResponseWriter, r *http.Request) {
params := &lib.ListParams{}
if err := UnmarshalParams(r, params); err != nil {
if err := lib.UnmarshalParams(r, params); err != nil {
util.WriteErrResponse(w, http.StatusBadRequest, err)
return
}
Expand Down Expand Up @@ -255,7 +255,7 @@ func (h *DatasetHandlers) listHandler(w http.ResponseWriter, r *http.Request) {
func (h *DatasetHandlers) getHandler(w http.ResponseWriter, r *http.Request) {
params := lib.GetParams{}

err := UnmarshalParams(r, &params)
err := lib.UnmarshalParams(r, &params)
if err != nil {
util.WriteErrResponse(w, http.StatusBadRequest, err)
return
Expand Down Expand Up @@ -350,7 +350,7 @@ func (h *DatasetHandlers) replyWithGetResponse(w http.ResponseWriter, r *http.Re

func (h *DatasetHandlers) diffHandler(w http.ResponseWriter, r *http.Request) {
params := &lib.DiffParams{}
err := UnmarshalParams(r, params)
err := lib.UnmarshalParams(r, params)
if err != nil {
util.WriteErrResponse(w, http.StatusBadRequest, err)
return
Expand All @@ -369,7 +369,7 @@ func (h *DatasetHandlers) diffHandler(w http.ResponseWriter, r *http.Request) {
func (h *DatasetHandlers) changesHandler(w http.ResponseWriter, r *http.Request) {
params := &lib.ChangeReportParams{}

err := UnmarshalParams(r, params)
err := lib.UnmarshalParams(r, params)
if err != nil {
util.WriteErrResponse(w, http.StatusBadRequest, err)
return
Expand Down Expand Up @@ -420,7 +420,7 @@ func (h *DatasetHandlers) peerListHandler(w http.ResponseWriter, r *http.Request

func (h *DatasetHandlers) pullHandler(w http.ResponseWriter, r *http.Request) {
params := &lib.PullParams{}
if err := UnmarshalParams(r, params); err != nil {
if err := lib.UnmarshalParams(r, params); err != nil {
util.WriteErrResponse(w, http.StatusBadRequest, err)
return
}
Expand All @@ -442,7 +442,7 @@ func (h *DatasetHandlers) pullHandler(w http.ResponseWriter, r *http.Request) {

func (h *DatasetHandlers) saveHandler(w http.ResponseWriter, r *http.Request) {
params := &lib.SaveParams{}
err := UnmarshalParams(r, params)
err := lib.UnmarshalParams(r, params)
if err != nil {
log.Debugw("unmarshal dataset save error", "err", err)
util.WriteErrResponse(w, http.StatusBadRequest, err)
Expand Down Expand Up @@ -475,7 +475,7 @@ func (h *DatasetHandlers) saveHandler(w http.ResponseWriter, r *http.Request) {

func (h *DatasetHandlers) removeHandler(w http.ResponseWriter, r *http.Request) {
params := lib.RemoveParams{}
err := UnmarshalParams(r, &params)
err := lib.UnmarshalParams(r, &params)
if err != nil {
util.WriteErrResponse(w, http.StatusBadRequest, err)
return
Expand Down Expand Up @@ -508,7 +508,7 @@ func (h *DatasetHandlers) removeHandler(w http.ResponseWriter, r *http.Request)

func (h DatasetHandlers) validateHandler(w http.ResponseWriter, r *http.Request) {
params := &lib.ValidateParams{}
err := UnmarshalParams(r, params)
err := lib.UnmarshalParams(r, params)
if err != nil {
util.WriteErrResponse(w, http.StatusBadRequest, err)
return
Expand All @@ -526,7 +526,7 @@ func (h DatasetHandlers) validateHandler(w http.ResponseWriter, r *http.Request)

func (h DatasetHandlers) renameHandler(w http.ResponseWriter, r *http.Request) {
params := &lib.RenameParams{}
err := UnmarshalParams(r, params)
err := lib.UnmarshalParams(r, params)
if err != nil {
util.WriteErrResponse(w, http.StatusBadRequest, err)
return
Expand Down Expand Up @@ -570,7 +570,7 @@ func (h DatasetHandlers) unpackHandler(w http.ResponseWriter, r *http.Request, p

func (h DatasetHandlers) manifestHandler(w http.ResponseWriter, r *http.Request) {
params := &lib.ManifestParams{}
err := UnmarshalParams(r, params)
err := lib.UnmarshalParams(r, params)
if err != nil {
util.WriteErrResponse(w, http.StatusBadRequest, err)
return
Expand All @@ -588,7 +588,7 @@ func (h DatasetHandlers) manifestHandler(w http.ResponseWriter, r *http.Request)

func (h DatasetHandlers) manifestMissingHandler(w http.ResponseWriter, r *http.Request) {
params := &lib.ManifestMissingParams{}
err := UnmarshalParams(r, params)
err := lib.UnmarshalParams(r, params)
if err != nil {
util.WriteErrResponse(w, http.StatusBadRequest, err)
return
Expand All @@ -606,7 +606,7 @@ func (h DatasetHandlers) manifestMissingHandler(w http.ResponseWriter, r *http.R

func (h DatasetHandlers) dagInfoHandler(w http.ResponseWriter, r *http.Request) {
params := &lib.DAGInfoParams{}
err := UnmarshalParams(r, params)
err := lib.UnmarshalParams(r, params)
if err != nil {
util.WriteErrResponse(w, http.StatusBadRequest, err)
return
Expand Down
10 changes: 5 additions & 5 deletions api/datasets_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ func TestParseGetParams(t *testing.T) {
}
setRefStringFromMuxVars(r)
args := &lib.GetParams{}
err := UnmarshalParams(r, args)
err := lib.UnmarshalParams(r, args)
if err != nil {
t.Error(err)
return
Expand Down Expand Up @@ -340,7 +340,7 @@ func TestParseGetParams(t *testing.T) {
}
setRefStringFromMuxVars(r)
args := &lib.GetParams{}
err := UnmarshalParams(r, args)
err := lib.UnmarshalParams(r, args)
if err == nil {
t.Errorf("case %d: expected error, but did not get one", i)
return
Expand All @@ -359,7 +359,7 @@ func TestParseGetParamsAcceptHeader(t *testing.T) {
r = mux.SetURLVars(r, map[string]string{"peername": "peer", "name": "my_ds"})
setRefStringFromMuxVars(r)
args := &lib.GetParams{}
err := UnmarshalParams(r, args)
err := lib.UnmarshalParams(r, args)
if err != nil {
t.Fatal(err)
}
Expand All @@ -380,7 +380,7 @@ func TestParseGetParamsAcceptHeader(t *testing.T) {
r = mux.SetURLVars(r, map[string]string{"peername": "peer", "name": "my_ds"})
setRefStringFromMuxVars(r)
args = &lib.GetParams{}
err = UnmarshalParams(r, args)
err = lib.UnmarshalParams(r, args)
if err != nil {
t.Fatal(err)
}
Expand All @@ -394,7 +394,7 @@ func TestParseGetParamsAcceptHeader(t *testing.T) {
r = mux.SetURLVars(r, map[string]string{"peername": "peer", "name": "my_ds"})
setRefStringFromMuxVars(r)
args = &lib.GetParams{}
err = UnmarshalParams(r, args)
err = lib.UnmarshalParams(r, args)
if err == nil {
t.Error("expected to get an error, but did not get one")
}
Expand Down
Loading