Skip to content
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
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,8 @@

# Output of the go coverage tool, specifically when used with LiteIDE
*.out

# editors
.idea
.DS_Store
.vscode
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 Roshan Gade

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
23 changes: 16 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,16 @@ REST API framework for go lang

# Framework is under development
## Status:
- Working on POC as per concept
Released alpha version
<br>
See examples
- Request Interceptors/Middlewares
- Routes with URL pattern
- Methods [GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH]
- Extend routes with namespace
- Error handler
- HTTP, HTTPS support

```
var api rest.API

Expand All @@ -13,22 +22,22 @@ api.Use(func(ctx *rest.Context) {
})

// routes
api.GET("/", func(ctx *rest.Context) {
ctx.Send("Hello World!")
api.Get("/", func(ctx *rest.Context) {
ctx.Text("Hello World!")
})

api.GET("/foo", func(ctx *rest.Context) {
api.Get("/foo", func(ctx *rest.Context) {
ctx.Status(401).Throw(errors.New("UNAUTHORIZED"))
})

api.GET("/:bar", func(ctx *rest.Context) {
api.Get("/:bar", func(ctx *rest.Context) {
fmt.Println("authtoken", ctx.Get("authtoken"))
ctx.SendJSON(ctx.Params)
ctx.JSON(ctx.Params)
})

// error handler
api.Error("UNAUTHORIZED", func(ctx *rest.Context) {
ctx.Send("You are unauthorized")
ctx.Text("You are unauthorized")
})

fmt.Println("Starting server.")
Expand Down
188 changes: 188 additions & 0 deletions api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
/*!
* rest-api-framework
* Copyright(c) 2019 Roshan Gade
* MIT Licensed
*/
package rest

import (
"errors"
"fmt"
"github.com/go-rs/rest-api-framework/utils"
"net/http"
"regexp"
)

type Handler func(ctx *Context)

/**
* API - Application
*/
type API struct {
prefix string
routes []route
interceptors []interceptor
exceptions []exception
unhandled Handler
}

/**
* Route
*/
type route struct {
method string
pattern string
regex *regexp.Regexp
params []string
handle Handler
}

/**
* Request interceptor
*/
type interceptor struct {
handle Handler
}

/**
* Exception Route
*/
type exception struct {
message string
handle Handler
}

/**
* Common Route
*/
func (api *API) Route(method string, pattern string, handle Handler) {
regex, params, err := utils.Compile(pattern)
if err != nil {
fmt.Println("Error in pattern", err)
panic(1)
}
api.routes = append(api.routes, route{
method: method,
pattern: pattern,
regex: regex,
params: params,
handle: handle,
})
}

/**
* Required handle for http module
*/
func (api API) ServeHTTP(res http.ResponseWriter, req *http.Request) {

urlPath := []byte(req.URL.Path)

ctx := Context{
Request: req,
Response: res,
}

// STEP 1: initialize context
ctx.init()
defer ctx.destroy()

// STEP 2: execute all interceptors
for _, task := range api.interceptors {
if ctx.end || ctx.err != nil {
break
}

task.handle(&ctx)
}

// STEP 3: check routes
for _, route := range api.routes {
if ctx.end || ctx.err != nil {
break
}

if (route.method == "" || route.method == req.Method) && route.regex.Match(urlPath) {
ctx.found = route.method != "" //?
ctx.Params = utils.Exec(route.regex, route.params, urlPath)
route.handle(&ctx)
}
}

// STEP 4: check handled exceptions
for _, exp := range api.exceptions {
if ctx.end || ctx.err == nil {
break
}

if exp.message == ctx.err.Error() {
exp.handle(&ctx)
}
}

// STEP 5: unhandled exceptions
if !ctx.end {
if ctx.err == nil && !ctx.found {
ctx.err = errors.New("URL_NOT_FOUND")
}

if api.unhandled != nil {
api.unhandled(&ctx)
}
}

// STEP 6: system handle
if !ctx.end {
ctx.unhandledException()
}
}

func (api *API) Use(handle Handler) {
task := interceptor{
handle: handle,
}
api.interceptors = append(api.interceptors, task)
}

func (api *API) All(pattern string, handle Handler) {
api.Route("", pattern, handle)
}

func (api *API) Get(pattern string, handle Handler) {
api.Route("GET", pattern, handle)
}

func (api *API) Post(pattern string, handle Handler) {
api.Route("POST", pattern, handle)
}

func (api *API) Put(pattern string, handle Handler) {
api.Route("PUT", pattern, handle)
}

func (api *API) Delete(pattern string, handle Handler) {
api.Route("DELETE", pattern, handle)
}

func (api *API) Options(pattern string, handle Handler) {
api.Route("OPTIONS", pattern, handle)
}

func (api *API) Head(pattern string, handle Handler) {
api.Route("HEAD", pattern, handle)
}

func (api *API) Patch(pattern string, handle Handler) {
api.Route("PATCH", pattern, handle)
}

func (api *API) Exception(err string, handle Handler) {
exp := exception{
message: err,
handle: handle,
}
api.exceptions = append(api.exceptions, exp)
}

func (api *API) UnhandledException(handle Handler) {
api.unhandled = handle
}
Loading