Skip to content

Commit

Permalink
Merge pull request #15 from didikprabowo/enhance/routes/handle
Browse files Browse the repository at this point in the history
Routes ::: handle route and remove cache routes
  • Loading branch information
didikprabowo authored Jan 1, 2021
2 parents 7ea745e + 517a031 commit 9b4aa54
Show file tree
Hide file tree
Showing 5 changed files with 190 additions and 16 deletions.
19 changes: 19 additions & 0 deletions _exanple/quick/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package main

import (
"fmt"

"github.com/didikprabowo/dipra"
)

func main() {
d := dipra.Default()

d.GET("/quick", func(c *dipra.Context) error {
return c.JSON(200, "WELCOME")
})

if err := d.Run(":9020"); err != nil {
fmt.Println(err)
}
}
2 changes: 1 addition & 1 deletion context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ func TestParam(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/user/OK/Created", strings.NewReader(pdataStr))
response := httptest.NewRecorder()

d.AddToObjectEngine("/user/:name/:status", http.MethodGet, nil)
d.AddRoute("/user/:name/:status", http.MethodGet, nil)
c := d.InitialContext(response, req)
d.HandlerRoute(c)

Expand Down
41 changes: 26 additions & 15 deletions dipra.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ func (e *Engine) Debug(debug bool) {
e.IsDebug = debug
}

// InitialContext ...
// InitialContext to define
func (e *Engine) InitialContext(w http.ResponseWriter, r *http.Request) *Context {
c := &Context{
ResponseWriter: w,
Expand All @@ -121,10 +121,19 @@ func (e *Engine) InitialContext(w http.ResponseWriter, r *http.Request) *Context
return c
}

// AddToObjectEngine is used for set routing and middleware
func (e *Engine) AddToObjectEngine(path, method string, handler HandlerFunc, middleware ...MiddlewareFunc) {
// AddRoute is used for set routing(path,mehtod, handle),
// By besides be able to set middleware
func (e *Engine) AddRoute(path, method string, handler HandlerFunc, middleware ...MiddlewareFunc) {

if exist := e.findRouter(method, path, handler); !exist {
e.Route = append(e.Route,
Route{Path: e.Prefix + path,
Method: method,
Handler: handler,
})
}

e.HandleMiddleware = append(e.HandleMiddleware, middleware...)
e.Route = append(e.Route, Route{Path: e.Prefix + path, Method: method, Handler: handler})
}

// Use is used for add handlefuncs
Expand All @@ -141,42 +150,42 @@ func (e *Engine) Group(group string, m ...MiddlewareFunc) *Engine {

// GET is used HTTP Request with GET METHOD
func (e *Engine) GET(path string, handler HandlerFunc, middleware ...MiddlewareFunc) {
e.AddToObjectEngine(path, http.MethodGet, handler, middleware...)
e.AddRoute(path, http.MethodGet, handler, middleware...)
}

// POST is used HTTP Request with POST METHOD
func (e *Engine) POST(path string, handler HandlerFunc, middleware ...MiddlewareFunc) {
e.AddToObjectEngine(path, http.MethodPost, handler, middleware...)
e.AddRoute(path, http.MethodPost, handler, middleware...)
}

// PUT is used HTTP Request with PUT METHOD
func (e *Engine) PUT(path string, handler HandlerFunc, middleware ...MiddlewareFunc) {
e.AddToObjectEngine(path, http.MethodPut, handler, middleware...)
e.AddRoute(path, http.MethodPut, handler, middleware...)
}

// PATCH is used HTTP Request with PATCH METHOD
func (e *Engine) PATCH(path string, handler HandlerFunc, middleware ...MiddlewareFunc) {
e.AddToObjectEngine(path, http.MethodPatch, handler, middleware...)
e.AddRoute(path, http.MethodPatch, handler, middleware...)
}

// DELETE is used HTTP Request with DELETE METHOD
func (e *Engine) DELETE(path string, handler HandlerFunc, middleware ...MiddlewareFunc) {
e.AddToObjectEngine(path, http.MethodDelete, handler, middleware...)
e.AddRoute(path, http.MethodDelete, handler, middleware...)
}

// OPTION is used HTTP Request with OPTION METHOD
func (e *Engine) OPTION(path string, handler HandlerFunc, middleware ...MiddlewareFunc) {
e.AddToObjectEngine(path, http.MethodOptions, handler, middleware...)
e.AddRoute(path, http.MethodOptions, handler, middleware...)
}

// TRACE is used HTTP Request with TRACE METHOD
func (e *Engine) TRACE(path string, handler HandlerFunc, middleware ...MiddlewareFunc) {
e.AddToObjectEngine(path, http.MethodTrace, handler, middleware...)
e.AddRoute(path, http.MethodTrace, handler, middleware...)
}

// CONNECT is used HTTP Request with CONNECT METHOD
func (e *Engine) CONNECT(path string, handler HandlerFunc, middleware ...MiddlewareFunc) {
e.AddToObjectEngine(path, http.MethodConnect, handler, middleware...)
e.AddRoute(path, http.MethodConnect, handler, middleware...)
}

// Static is used define http to get file type
Expand All @@ -192,7 +201,7 @@ func (e *Engine) Static(prefix, root string) {
return c.File(name)
}

e.AddToObjectEngine(prefix+"/*", http.MethodGet, cp)
e.AddRoute(prefix+"/*", http.MethodGet, cp)
}

// defaulterrorHttp is used set error default
Expand Down Expand Up @@ -247,12 +256,14 @@ func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}

if e.HandleMiddleware != nil {
rt.Handler = e.WrapMiddleware(rt.Handler)
rt.Handler = e.addMiddleware(rt.Handler)
}

if err := rt.Handler(ctx); err != nil {
e.HandlerError(err, ctx)
}

e.Pool.Put(ctx)
}

// HandlerRoute is used running context http
Expand Down Expand Up @@ -285,7 +296,7 @@ func (e *Engine) HandlerRoute(c *Context) (r Route, werrx *WrapError) {
}

// WrapMiddleware is used wrapping with returns HandlerFunc
func (e *Engine) WrapMiddleware(h HandlerFunc) HandlerFunc {
func (e *Engine) addMiddleware(h HandlerFunc) HandlerFunc {
for i := len(e.HandleMiddleware) - 1; i >= 0; i-- {
if e.HandleMiddleware[i](h) != nil {
h = e.HandleMiddleware[i](h)
Expand Down
78 changes: 78 additions & 0 deletions router.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package dipra

import (
"log"
"net/http"
"regexp"
"strings"
)

var (
// List method is allowed
allowMethod = []string{
http.MethodGet,
http.MethodDelete,
http.MethodPost,
http.MethodConnect,
http.MethodPatch,
http.MethodPut,
}
)

// allowMethods for use check your define a method
func (e *Engine) allowMethods(m string) (ok bool) {
for _, mlist := range allowMethod {
if mlist == m {
return true
}
}
return ok
}

func (e *Engine) cleanPath(p string) string {
return strings.ReplaceAll(p, "/", "")
}

// allowPath for use check your path
func (e *Engine) allowPath(p string) (ok bool) {
p = e.cleanPath(p)
isAllow := regexp.MustCompile(`[a-zA-Z0-9]$`)
ok = isAllow.MatchString(p)

return ok
}

/*
findRouter for used to checking existing path,
method and handler
*/
func (e *Engine) findRouter(m, p string, h HandlerFunc) (exist bool) {

if ok := e.allowMethods(m); !ok {
log.Printf("Method %s not allow", m)
return
}

if ok := e.allowPath(p); !ok {
log.Printf("Path %s is invalid syntax", p)
return
}

toLower := func(s string) string {
return strings.ToLower(s)
}

for i := range e.getRoutes() {
if toLower(e.Route[i].Method) == toLower(m) &&
toLower(e.Route[i].Path) == toLower(p) {
e.Route[i].Handler = h
return true
}
}
return exist
}

// getRoutes for get The routes you define
func (e *Engine) getRoutes() []Route {
return e.Route
}
66 changes: 66 additions & 0 deletions router_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package dipra_test

import (
"net/http/httptest"
"testing"

. "github.com/didikprabowo/dipra"
"github.com/stretchr/testify/assert"
)

func TestRoutes(t *testing.T) {

d := Default()

t.Run("troute", func(t *testing.T) {
t.Run("single", func(t *testing.T) {
testTableRouteData := []Route{
Route{
Path: "/index",
Method: "GET",
Handler: func(c *Context) error {
return c.String(200, "OK")
},
},
}

for _, v := range testTableRouteData {
d.AddRoute(v.Path, v.Method, v.Handler)
}

req := httptest.NewRequest("GET", "/index", nil)
resp := httptest.NewRecorder()
d.ServeHTTP(resp, req)
assert.Equal(t, "OK", resp.Body.String())
})

t.Run("double", func(t *testing.T) {
testTableRouteData := []Route{
Route{
Path: "/index",
Method: "GET",
Handler: func(c *Context) error {
return c.String(200, "OK")
},
},
Route{
Path: "/index",
Method: "GET",
Handler: func(c *Context) error {
return c.String(200, "OKE")
},
},
}

for _, v := range testTableRouteData {
d.AddRoute(v.Path, v.Method, v.Handler)
}

req := httptest.NewRequest("GET", "/index", nil)
resp := httptest.NewRecorder()
d.ServeHTTP(resp, req)
assert.Equal(t, "OKE", resp.Body.String())
})
})

}

0 comments on commit 9b4aa54

Please sign in to comment.