1
0
mirror of https://github.com/aclindsa/moneygo.git synced 2024-11-01 00:10:06 -04:00

handlers: Cleanup Context, route handling code

This commit is contained in:
Aaron Lindsay 2017-11-12 20:38:22 -05:00
parent 507868b7a5
commit e99abfe866
2 changed files with 29 additions and 21 deletions

View File

@ -12,22 +12,31 @@ import (
type ResponseWriterWriter interface { type ResponseWriterWriter interface {
Write(http.ResponseWriter) error Write(http.ResponseWriter) error
} }
type Tx = gorp.Transaction
type Context struct {
Tx *Tx
User *User
Remaining string // portion of URL not yet reached in the hierarchy
}
type Handler func(*http.Request, *Context) ResponseWriterWriter
func NextLevel(previous string) (current, remaining string) { type Tx = gorp.Transaction
split := strings.SplitN(previous, "/", 2)
if len(split) == 2 { type Context struct {
return split[0], split[1] Tx *Tx
} User *User
return split[0], "" remainingURL string // portion of URL path not yet reached in the hierarchy
} }
func (c *Context) SetURL(url string) {
c.remainingURL = path.Clean("/" + url)[1:]
}
func (c *Context) NextLevel() string {
split := strings.SplitN(c.remainingURL, "/", 2)
if len(split) == 2 {
c.remainingURL = split[1]
} else {
c.remainingURL = ""
}
return split[0]
}
type Handler func(*http.Request, *Context) ResponseWriterWriter
type APIHandler struct { type APIHandler struct {
DB *gorp.DbMap DB *gorp.DbMap
} }
@ -59,15 +68,15 @@ func (ah *APIHandler) txWrapper(h Handler, r *http.Request, context *Context) (w
} }
func (ah *APIHandler) route(r *http.Request) ResponseWriterWriter { func (ah *APIHandler) route(r *http.Request) ResponseWriterWriter {
current, remaining := NextLevel(path.Clean("/" + r.URL.Path)[1:]) context := &Context{}
if current != "v1" { context.SetURL(r.URL.Path)
if context.NextLevel() != "v1" {
return NewError(3 /*Invalid Request*/) return NewError(3 /*Invalid Request*/)
} }
current, remaining = NextLevel(remaining) route := context.NextLevel()
context := &Context{Remaining: remaining}
switch current { switch route {
case "sessions": case "sessions":
return ah.txWrapper(SessionHandler, r, context) return ah.txWrapper(SessionHandler, r, context)
case "users": case "users":

View File

@ -348,10 +348,9 @@ func AccountImportHandler(context *Context, r *http.Request, user *User, account
} }
func ImportHandler(r *http.Request, context *Context) ResponseWriterWriter { func ImportHandler(r *http.Request, context *Context) ResponseWriterWriter {
current, remaining := NextLevel(context.Remaining) route := context.NextLevel()
if current != "gnucash" { if route != "gnucash" {
return NewError(3 /*Invalid Request*/) return NewError(3 /*Invalid Request*/)
} }
context.Remaining = remaining
return GnucashImportHandler(r, context) return GnucashImportHandler(r, context)
} }