Compare commits

..

No commits in common. "1aa9b78bdceb8a7055b285b2ece2c39d3937a17b" and "0ed626e35169d31b56b2581c6e0fbe0665f34d14" have entirely different histories.

6 changed files with 28 additions and 125 deletions

View File

@ -19,10 +19,7 @@ type Context struct {
ctx context.Context
request *http.Request
responseWriter http.ResponseWriter
handlers []ControllerHandler
// current handler index
index int
handler ControllerHandler
hasTimeout bool
writerMux *sync.Mutex
@ -35,7 +32,6 @@ func NewContext(w http.ResponseWriter, r *http.Request) *Context {
request: r,
responseWriter: w,
writerMux: &sync.Mutex{},
index: -1, // will be set to 0 when at the beginning
}
}
@ -101,25 +97,6 @@ func (ctx *Context) Value(key any) any {
return ctx.BaseContext().Value(key)
}
// Next runs the next function in the function chain
func (ctx *Context) Next() error {
ctx.index++
if ctx.index >= len(ctx.handlers) {
// This is the end of the chain
return nil
}
// Run this handler
if err := ctx.handlers[ctx.index](ctx); err != nil {
return err
}
return nil
}
// SetHandlers sets handlers for context
func (ctx *Context) SetHandlers(handlers []ControllerHandler) {
ctx.handlers = handlers
}
// }}}
// {{{ Implements request functions

View File

@ -30,37 +30,37 @@ func NewCore() *Core {
// Get is a simple get router
func (c *Core) Get(url string, handler ControllerHandler) {
upperUrl := strings.ToUpper(url)
if err := c.router["GET"].AddRouter(upperUrl, handler); err != nil {
log.Println(err)
}
if err := c.router["GET"].AddRouter(upperUrl, handler); err != nil{
log.Println(err)
}
}
// Post is a simple post router
func (c *Core) Post(url string, handler ControllerHandler) {
upperUrl := strings.ToUpper(url)
if err := c.router["POST"].AddRouter(upperUrl, handler); err != nil {
log.Println(err)
}
if err := c.router["POST"].AddRouter(upperUrl, handler); err != nil{
log.Println(err)
}
}
// Put is a simple put router
func (c *Core) Put(url string, handler ControllerHandler) {
upperUrl := strings.ToUpper(url)
if err := c.router["PUT"].AddRouter(upperUrl, handler); err != nil {
log.Println(err)
}
if err := c.router["PUT"].AddRouter(upperUrl, handler); err != nil{
log.Println(err)
}
}
// Delete is a simple delete router
func (c *Core) Delete(url string, handler ControllerHandler) {
upperUrl := strings.ToUpper(url)
if err := c.router["DELETE"].AddRouter(upperUrl, handler); err != nil {
log.Println(err)
}
if err := c.router["DELETE"].AddRouter(upperUrl, handler); err != nil{
log.Println(err)
}
}
// FindRouteByRequest finds route using the request
func (c *Core) FindRouteByRequest(r *http.Request) []ControllerHandler {
func (c *Core) FindRouteByRequest(r *http.Request) ControllerHandler {
upperUri := strings.ToUpper(r.URL.Path)
upperMethod := strings.ToUpper(r.Method)
@ -70,13 +70,13 @@ func (c *Core) FindRouteByRequest(r *http.Request) []ControllerHandler {
return nil
}
controllers := mapper.FindRoute(upperUri)
if controllers == nil {
controller := mapper.FindRoute(upperUri)
if controller == nil {
log.Printf("URI %q is not recognized\n", r.URL.Path)
return nil
}
return controllers
return controller
}
func (c *Core) Group(prefix string) IGroup {
@ -92,15 +92,14 @@ func (c *Core) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := NewContext(w, r)
handlers := c.FindRouteByRequest(r)
if handlers == nil {
router := c.FindRouteByRequest(r)
if router == nil {
ctx.WriteJSON(http.StatusNotFound, "Request not found")
return
}
ctx.SetHandlers(handlers)
if err := ctx.Next(); err != nil {
err := router(ctx)
if err != nil {
ctx.WriteJSON(http.StatusInternalServerError, "Internal error")
return
}

View File

@ -1,48 +0,0 @@
package middleware
import (
"context"
"log"
"net/http"
"time"
"git.vinchent.xyz/vinchent/go-web/framework"
)
func Timeout(d time.Duration) framework.ControllerHandler {
return func(c *framework.Context) error {
finish := make(chan struct{}, 1)
panicChan := make(chan interface{}, 1)
durationCtx, cancel := context.WithTimeout(c.BaseContext(), d)
defer cancel()
go func() {
// Handle panic
defer func() {
if p := recover(); p != nil {
panicChan <- p
}
}()
// Run the next middleware or the business logic
c.Next()
finish <- struct{}{}
}()
select {
case p := <-panicChan:
// panic
log.Println(p)
c.GetResponseWriter().WriteHeader(http.StatusInternalServerError)
case <-finish:
// finish normally
log.Println("finish")
case <-durationCtx.Done():
c.SetHasTimeout()
c.GetResponseWriter().Write([]byte("time out"))
}
return nil
}
}

View File

@ -1,25 +0,0 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"git.vinchent.xyz/vinchent/go-web/framework"
)
func TestTimeout(t *testing.T) {
t.Run("Test timeout handler", func(t *testing.T) {
timeoutHandler := Timeout(1 * time.Millisecond)
request := httptest.NewRequest(http.MethodGet, "/", nil)
response := httptest.NewRecorder()
c := framework.NewContext(response, request)
err := timeoutHandler(c)
if err != nil {
t.Fatal(err)
}
})
}

View File

@ -14,10 +14,10 @@ func NewTrie() *Trie {
return &Trie{root: newNode("")}
}
func (t *Trie) FindRoute(uri string) []ControllerHandler {
func (t *Trie) FindRoute(uri string) ControllerHandler {
uri = strings.TrimPrefix(uri, "/")
if uri == "" {
return t.root.handlers
return t.root.handler
}
found := t.root.findRoute(uri)
@ -25,14 +25,14 @@ func (t *Trie) FindRoute(uri string) []ControllerHandler {
return nil
}
return found.handlers
return found.handler
}
func (t *Trie) AddRouter(uri string, handler ControllerHandler) error {
uri = strings.TrimPrefix(uri, "/")
if uri == "" {
t.root.isLast = true
t.root.handlers = append(t.root.handlers, handler)
t.root.handler = handler
return nil
}
@ -54,7 +54,7 @@ func (t *Trie) AddRouter(uri string, handler ControllerHandler) error {
type node struct {
isLast bool
segment string
handlers []ControllerHandler
handler ControllerHandler
children []*node
}
@ -125,7 +125,7 @@ func (n *node) addRoute(uri string, handler ControllerHandler) error {
} else {
// otherwise, set the child
child.isLast = true
child.handlers = append(child.handlers, handler)
child.handler = handler
return nil
}
}
@ -138,7 +138,7 @@ func (n *node) addRoute(uri string, handler ControllerHandler) error {
new := newNode(splitted[0])
if isLast {
// this is the end
new.handlers = append(new.handlers, handler)
new.handler = handler
new.isLast = true
n.children = append(n.children, new)
return nil

0
go.sum
View File