Skip to content

Commit

Permalink
Merge pull request #7 from savsgio/develop
Browse files Browse the repository at this point in the history
Code refactor and improvments
  • Loading branch information
Sergio Andrés Virviescas Santana authored Jul 16, 2018
2 parents a3a2519 + 0dbb111 commit f227e45
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 29 deletions.
14 changes: 10 additions & 4 deletions atreugo.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,14 @@ type View func(ctx *fasthttp.RequestCtx) error
// Middleware must process all incoming requests before defined views.
type Middleware func(ctx *fasthttp.RequestCtx) (int, error)

// AllowedHTTPMethods all http methods that Atruego supports
var AllowedHTTPMethods = []string{"GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH", "DELETE"}

// New create a new instance of Atreugo Server
func New(cfg *Config) *Atreugo {
if cfg.LogLevel == "" {
cfg.LogLevel = logger.INFO
}
log := logger.New("atreugo", cfg.LogLevel, os.Stdout)

router := fasthttprouter.New()

Expand All @@ -62,7 +64,7 @@ func New(cfg *Config) *Atreugo {
Name: "AtreugoFastHTTPServer",
ReadTimeout: 25 * time.Second,
},
log: log,
log: logger.New("atreugo", cfg.LogLevel, os.Stdout),
cfg: cfg,
}

Expand All @@ -77,7 +79,7 @@ func (s *Atreugo) viewHandler(viewFn View) fasthttp.RequestHandler {
if statusCode, err := middlewareFn(ctx); err != nil {
s.log.Errorf("Msg: %v | RequestUri: %s", err, ctx.URI().String())

JsonResponse(ctx, Json{"Error": err.Error()}, statusCode)
JSONResponse(ctx, JSON{"Error": err.Error()}, statusCode)
return
}
}
Expand Down Expand Up @@ -147,7 +149,11 @@ func (s *Atreugo) Static(rootStaticDirPath string) {

// Path add the views to serve
func (s *Atreugo) Path(httpMethod string, url string, viewFn View) {
callFuncByName(s.router, httpMethod, url, s.viewHandler(viewFn))
if !include(AllowedHTTPMethods, httpMethod) {
panic("Invalid http method '" + httpMethod + "' for the url " + url)
}

s.router.Handle(httpMethod, url, s.viewHandler(viewFn))
}

// UseMiddleware register middleware functions that viewHandler will use
Expand Down
6 changes: 2 additions & 4 deletions examples/jwt_auth_middleware_sever/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func main() {
server.UseMiddleware(checkTokenMiddleware)

server.Path("GET", "/", func(ctx *fasthttp.RequestCtx) error {
return atreugo.HttpResponse(ctx,
return atreugo.HTTPResponse(ctx,
[]byte(fmt.Sprintf(`<h1>You are login with JWT</h1>
JWT cookie value: %s`, ctx.Request.Header.Cookie("atreugo_jwt"))))
})
Expand All @@ -111,9 +111,7 @@ func main() {
ctx.Response.Header.SetCookie(cookie)
}

ctx.Redirect("/", ctx.Response.StatusCode())

return nil
return atreugo.RedirectResponse(ctx, "/", ctx.Response.StatusCode())
})

err := server.ListenAndServe()
Expand Down
4 changes: 2 additions & 2 deletions examples/simple_server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ func main() {
server.UseMiddleware(fnMiddlewareOne, fnMiddlewareTwo)

server.Path("GET", "/", func(ctx *fasthttp.RequestCtx) error {
return atreugo.HttpResponse(ctx, []byte("<h1>Atreugo Micro-Framework</h1>"))
return atreugo.HTTPResponse(ctx, []byte("<h1>Atreugo Micro-Framework</h1>"))
})

server.Path("GET", "/jsonPage", func(ctx *fasthttp.RequestCtx) error {
return atreugo.JsonResponse(ctx, atreugo.Json{"Atreugo": true})
return atreugo.JSONResponse(ctx, atreugo.JSON{"Atreugo": true})
})

err := server.ListenAndServe()
Expand Down
17 changes: 14 additions & 3 deletions response.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ import (
"github.com/erikdubbelboer/fasthttp"
)

type Json map[string]interface{}
// JSON is a map whose key is a string and whose value an interface
type JSON map[string]interface{}

func JsonResponse(ctx *fasthttp.RequestCtx, response interface{}, statusCode ...int) error {
// JSONResponse return http response with content-type application/json
func JSONResponse(ctx *fasthttp.RequestCtx, response interface{}, statusCode ...int) error {
ctx.SetContentType("application/json")

if len(statusCode) > 0 {
Expand All @@ -21,7 +23,8 @@ func JsonResponse(ctx *fasthttp.RequestCtx, response interface{}, statusCode ...
return json.NewEncoder(ctx).Encode(response)
}

func HttpResponse(ctx *fasthttp.RequestCtx, response []byte, statusCode ...int) error {
// HTTPResponse return http response with content-type text/html; charset=utf-8
func HTTPResponse(ctx *fasthttp.RequestCtx, response []byte, statusCode ...int) error {
ctx.SetContentType("text/html; charset=utf-8")

if len(statusCode) > 0 {
Expand All @@ -35,3 +38,11 @@ func HttpResponse(ctx *fasthttp.RequestCtx, response []byte, statusCode ...int)
_, err := ctx.Write(response)
return err
}

// RedirectResponse redirect request to an especific url
func RedirectResponse(ctx *fasthttp.RequestCtx, url string, statusCode int) error {
ctx.ResetBody()
ctx.Redirect(url, statusCode)

return nil
}
32 changes: 16 additions & 16 deletions utils.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package atreugo

import (
"fmt"
"reflect"
"unsafe"
)

Expand All @@ -12,22 +10,24 @@ func panicOnError(err error) {
}
}

func callFuncByName(class interface{}, funcName string, params ...interface{}) []reflect.Value {
fn := reflect.ValueOf(class).MethodByName(funcName)

if !fn.IsValid() {
panic(fmt.Errorf("Method not found \"%s\"", funcName))
}
// B2S convert bytes array to string without memory allocation (non safe)
func B2S(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}

args := make([]reflect.Value, len(params))
for i, param := range params {
args[i] = reflect.ValueOf(param)
// index returns the first index of the target string `t`, or
// -1 if no match is found.
func indexOf(vs []string, t string) int {
for i, v := range vs {
if v == t {
return i
}
}

return fn.Call(args)
return -1
}

// B2S convert bytes array to string without memory allocation
func B2S(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
// include returns `true` if the target string t is in the
// slice.
func include(vs []string, t string) bool {
return indexOf(vs, t) >= 0
}

0 comments on commit f227e45

Please sign in to comment.