Skip to content

Commit

Permalink
update some for code layout
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Sep 29, 2020
1 parent 5c7763a commit 407b249
Show file tree
Hide file tree
Showing 11 changed files with 213 additions and 199 deletions.
16 changes: 1 addition & 15 deletions context_render.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,6 @@ import (
"github.com/gookit/rux/render"
)

const (
// ContentType header key
ContentType = "Content-Type"
// ContentBinary represents content type application/octet-stream
ContentBinary = "application/octet-stream"

// ContentDisposition describes contentDisposition
ContentDisposition = "Content-Disposition"
// describes content disposition type
dispositionInline = "inline"
// describes content disposition type
dispositionAttachment = "attachment"
)

// ShouldRender render and response to client
func (c *Context) ShouldRender(status int, obj interface{}, renderer render.Renderer) error {
c.SetStatus(status)
Expand All @@ -43,7 +29,7 @@ func (c *Context) Respond(status int, obj interface{}, renderer render.Renderer)

err := renderer.Render(c.Resp, obj)
if err != nil {
panic(err)
panic(err) // TODO or use AddError()
}
}

Expand Down
145 changes: 145 additions & 0 deletions define.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
package rux

import (
"net/http"
"regexp"
"sort"
"strconv"
"strings"
)

const (
anyMatch = `[^/]+`
)

const (
// ContentType header key
ContentType = "Content-Type"
// ContentBinary represents content type application/octet-stream
ContentBinary = "application/octet-stream"

// ContentDisposition describes contentDisposition
ContentDisposition = "Content-Disposition"
// describes content disposition type
dispositionInline = "inline"
// describes content disposition type
dispositionAttachment = "attachment"
)

const (
// CTXMatchResult key name in the context
// CTXMatchResult = "_matchResult"

// CTXRecoverResult key name in the context
CTXRecoverResult = "_recoverResult"
// CTXAllowedMethods key name in the context
CTXAllowedMethods = "_allowedMethods"
// CTXCurrentRouteName key name in the context
CTXCurrentRouteName = "_currentRouteName"
// CTXCurrentRoutePath key name in the context
CTXCurrentRoutePath = "_currentRoutePath"
)

type routes []*Route

// like "GET": [ Route, ...]
type methodRoutes map[string]routes

// ControllerFace a simple controller interface
type ControllerFace interface {
// AddRoutes for support register routes in the controller.
AddRoutes(g *Router)
}

var (
debug bool
// current supported HTTP method
// all supported methods string, use for method check
// more: ,COPY,PURGE,LINK,UNLINK,LOCK,UNLOCK,VIEW,SEARCH
anyMethods = []string{GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD, CONNECT, TRACE}
)

// RESTFul method names definition
var (
IndexAction = "Index"
CreateAction = "Create"
StoreAction = "Store"
ShowAction = "Show"
EditAction = "Edit"
UpdateAction = "Update"
DeleteAction = "Delete"

// RESTFul action methods definition
RESTFulActions = map[string][]string{
IndexAction: {GET},
CreateAction: {GET},
StoreAction: {POST},
ShowAction: {GET},
EditAction: {GET},
UpdateAction: {PUT, PATCH},
DeleteAction: {DELETE},
}
)

/*************************************************************
* Route Params/Info
*************************************************************/

// RouteInfo simple route info struct
type RouteInfo struct {
Name, Path, HandlerName string
// supported method of the route
Methods []string
HandlerNum int
}

// Params for current route
type Params map[string]string

// Has param key in the Params
func (p Params) Has(key string) bool {
_, ok := p[key]
return ok
}

// String get string value by key
func (p Params) String(key string) (val string) {
if val, ok := p[key]; ok {
return val
}
return
}

// Int get int value by key
func (p Params) Int(key string) (val int) {
if str, ok := p[key]; ok {
val, err := strconv.Atoi(str)
if err == nil {
return val
}
}
return
}

/*************************************************************
* internal vars
*************************************************************/

// "/users/{id}" "/users/{id:\d+}" `/users/{uid:\d+}/blog/{id}`
var varRegex = regexp.MustCompile(`{[^/]+}`)

var internal404Handler HandlerFunc = func(c *Context) {
http.NotFound(c.Resp, c.Req)
}

var internal405Handler HandlerFunc = func(c *Context) {
allowed := c.MustGet(CTXAllowedMethods).([]string)
sort.Strings(allowed)
c.SetHeader("Allow", strings.Join(allowed, ", "))

if c.Req.Method == OPTIONS {
c.SetStatus(200)
} else {
http.Error(c.Resp, "Method not allowed", 405)
}
}
32 changes: 0 additions & 32 deletions dispatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import (
"net"
"net/http"
"os"
"sort"
"strings"
)

/*************************************************************
Expand Down Expand Up @@ -83,36 +81,6 @@ func (r *Router) WrapHTTPHandlers(preHandlers ...func(h http.Handler) http.Handl
* dispatch http request
*************************************************************/

const (
// CTXMatchResult key name in the context
// CTXMatchResult = "_matchResult"

// CTXRecoverResult key name in the context
CTXRecoverResult = "_recoverResult"
// CTXAllowedMethods key name in the context
CTXAllowedMethods = "_allowedMethods"
// CTXCurrentRouteName key name in the context
CTXCurrentRouteName = "_currentRouteName"
// CTXCurrentRoutePath key name in the context
CTXCurrentRoutePath = "_currentRoutePath"
)

var internal404Handler HandlerFunc = func(c *Context) {
http.NotFound(c.Resp, c.Req)
}

var internal405Handler HandlerFunc = func(c *Context) {
allowed := c.MustGet(CTXAllowedMethods).([]string)
sort.Strings(allowed)
c.SetHeader("Allow", strings.Join(allowed, ", "))

if c.Req.Method == OPTIONS {
c.SetStatus(200)
} else {
http.Error(c.Resp, "Method not allowed", 405)
}
}

// ServeHTTP for handle HTTP request, response data to client.
func (r *Router) ServeHTTP(res http.ResponseWriter, req *http.Request) {
// get new context
Expand Down
2 changes: 1 addition & 1 deletion extends.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func (c *Context) Render(status int, name string, data interface{}) (err error)

// Validate context validator
// Deprecated
// please use ShouldBind(), it will auto call validator
// please use ShouldBind(), it will auto call validator.
func (c *Context) Validate(i interface{}) error {
if c.Router().Validator == nil {
return errors.New("validator not registered")
Expand Down
6 changes: 3 additions & 3 deletions middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,16 @@ import (
// HandlerFunc a handler definition
type HandlerFunc func(c *Context)

// HandlersChain middleware handlers chain definition
type HandlersChain []HandlerFunc

// ServeHTTP implement the http.Handler
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c := &Context{}
c.Init(w, r)
f(c)
}

// HandlersChain middleware handlers chain definition
type HandlersChain []HandlerFunc

// Last returns the last handler in the chain. ie. the last handler is the main own.
func (c HandlersChain) Last() HandlerFunc {
length := len(c)
Expand Down
7 changes: 0 additions & 7 deletions parse_match.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,6 @@ import (
* route parse
*************************************************************/

const (
anyMatch = `[^/]+`
)

// "/users/{id}" "/users/{id:\d+}" `/users/{uid:\d+}/blog/{id}`
var varRegex = regexp.MustCompile(`{[^/]+}`)

// Parsing routes with parameters
func (r *Router) parseParamRoute(route *Route) (first string) {
path := route.path
Expand Down
41 changes: 0 additions & 41 deletions route.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,9 @@ import (
"fmt"
"net/url"
"regexp"
"strconv"
"strings"
)

/*************************************************************
* Route Params
*************************************************************/

// Params for current route
type Params map[string]string

// Has param key in the Params
func (p Params) Has(key string) bool {
_, ok := p[key]
return ok
}

// String get string value by key
func (p Params) String(key string) (val string) {
if val, ok := p[key]; ok {
return val
}
return
}

// Int get int value by key
func (p Params) Int(key string) (val int) {
if str, ok := p[key]; ok {
val, err := strconv.Atoi(str)
if err == nil {
return val
}
}
return
}

/*************************************************************
* Route definition
*************************************************************/
Expand Down Expand Up @@ -77,14 +44,6 @@ type Route struct {
// defaults
}

// RouteInfo simple route info struct
type RouteInfo struct {
Name, Path, HandlerName string
// supported method of the route
Methods []string
HandlerNum int
}

// NewRoute create a new route
func NewRoute(path string, handler HandlerFunc, methods ...string) *Route {
return &Route{
Expand Down
4 changes: 4 additions & 0 deletions route_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import (
"sync"
)

/*************************************************************
* Route Caches TODO move to extends.go
*************************************************************/

// cacheNode struct
type cacheNode struct {
Key string
Expand Down
Loading

0 comments on commit 407b249

Please sign in to comment.