Skip to content

fix: remove plus path parameter #58

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jan 1, 2024
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
34 changes: 24 additions & 10 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@ const contentTypeHeader string = "Content-Type"
// Context is the context of current HTTP request.
// It holds data related to current HTTP request.
type Context struct {
request *http.Request
response ResponseWriter
params Params
storage Map
kid *Kid
lock sync.Mutex
request *http.Request
response ResponseWriter
params Params
storage Map
kid *Kid
lock sync.Mutex
routeName string
}

// newContext returns a new empty context.
Expand All @@ -32,13 +33,19 @@ func (c *Context) reset(request *http.Request, response http.ResponseWriter) {
c.response = newResponse(response)
c.storage = make(Map)
c.params = make(Params)
c.routeName = ""
}

// setParams sets request's path parameters.
func (c *Context) setParams(params Params) {
c.params = params
}

// setRouteName sets the route name.
func (c *Context) setRouteName(name string) {
c.routeName = name
}

// Request returns plain request of current HTTP request.
func (c *Context) Request() *http.Request {
return c.request
Expand Down Expand Up @@ -68,6 +75,12 @@ func (c *Context) Path() string {
return u.Path
}

// Route returns current request's route name.
// It's the user entered path, e.g. /greet/{name}.
func (c *Context) Route() string {
return c.routeName
}

// Method returns request method.
func (c *Context) Method() string {
return c.request.Method
Expand Down Expand Up @@ -251,10 +264,11 @@ func (c *Context) Get(key string) (any, bool) {
// Writes to the response of a cloned context will panic.
func (c *Context) Clone() *Context {
ctx := Context{
request: c.request.Clone(context.Background()),
response: c.response.(*response).clone(),
kid: c.kid,
lock: sync.Mutex{},
request: c.request.Clone(context.Background()),
response: c.response.(*response).clone(),
kid: c.kid,
lock: sync.Mutex{},
routeName: c.routeName,
}

// Copy path params.
Expand Down
8 changes: 8 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -592,3 +592,11 @@ func TestContext_Clone(t *testing.T) {
clonedCtx.Response().Status()
})
}

func TestContext_Route(t *testing.T) {
ctx := newContext(New())

ctx.setRouteName("route_name")

assert.Equal(t, "route_name", ctx.Route())
}
5 changes: 4 additions & 1 deletion kid.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ type (
)

// Version of Kid.
const Version string = "v0.3.0"
const Version string = "v0.4.0"

// allMethods is a list of all HTTP methods.
var allMethods = []string{
Expand Down Expand Up @@ -230,11 +230,14 @@ func (k *Kid) ServeHTTP(w http.ResponseWriter, r *http.Request) {

if err == errNotFound {
handler = k.applyMiddlewaresToHandler(k.notFoundHandler, k.middlewares...)
c.setRouteName("Not Found")
} else if err == errMethodNotAllowed {
handler = k.applyMiddlewaresToHandler(k.methodNotAllowedHandler, k.middlewares...)
c.setRouteName("Method Not Allowed")
} else {
handler = k.applyMiddlewaresToHandler(route.handler, route.middlewares...)
handler = k.applyMiddlewaresToHandler(handler, k.middlewares...)
c.setRouteName(route.name)
}

handler(c)
Expand Down
7 changes: 4 additions & 3 deletions middlewares/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,15 +98,16 @@ func NewLoggerWithConfig(cfg LoggerConfig) kid.MiddlewareFunc {
next(c)

end := time.Now()
duration := end.Sub(start)
elapsed := end.Sub(start)

status := c.Response().Status()

attrs := []slog.Attr{
slog.Time("time", end),
slog.Duration("latency_ns", duration),
slog.String("latency", duration.String()),
slog.Int64("latency_ms", elapsed.Milliseconds()),
slog.String("latency", elapsed.String()),
slog.Int("status", status),
slog.String("route", c.Route()),
slog.String("path", c.Path()),
slog.String("method", c.Method()),
slog.String("user_agent", c.GetRequestHeader("User-Agent")),
Expand Down
6 changes: 4 additions & 2 deletions middlewares/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@ import (
type logRecord struct {
Msg string `json:"msg"`
Time time.Time `json:"time"`
LatenyNS int64 `json:"latency_ns"`
LatenyMS int64 `json:"latency_ms"`
Latency string `json:"latency"`
Status int `json:"status"`
Route string `json:"route"`
Path string `json:"path"`
Method string `json:"method"`
UserAgent string `json:"user_agent"`
Expand Down Expand Up @@ -119,11 +120,12 @@ func TestNewLoggerWithConfig(t *testing.T) {

assert.Equal(t, testCase.status, logRecord.Status)
assert.Equal(t, testCase.path, logRecord.Path)
assert.Equal(t, testCase.path, logRecord.Route)
assert.Equal(t, http.MethodGet, logRecord.Method)
assert.Equal(t, "Go Test", logRecord.UserAgent)
assert.NotZero(t, logRecord.Time)
assert.NotEmpty(t, logRecord.Latency)
assert.NotEmpty(t, logRecord.LatenyNS)
assert.NotEmpty(t, logRecord.LatenyMS)
assert.Equal(t, testCase.msg, logRecord.Msg)
})
}
Expand Down
15 changes: 11 additions & 4 deletions tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,20 @@ var (
const (
paramPrefix = "{"
paramSuffix = "}"
plusParamPrefix = paramPrefix + "+"
starParamPrefix = paramPrefix + "*"
)

type (
// handlerMiddleware zips a handler and its middlewares to each other.
handlerMiddleware struct {
handler HandlerFunc
// handler is the route request handler.
handler HandlerFunc

// middlewares is route middlewares.
middlewares []MiddlewareFunc

// name is route name.
name string
}

// Tree is a tree used for routing.
Expand Down Expand Up @@ -112,11 +117,12 @@ func (t *Tree) insertNode(path string, methods []string, middlewares []Middlewar
currNode = child
}
} else { // Only for the last iteration of the for loop.
hm := handlerMiddleware{handler: handler, middlewares: middlewares, name: path}
if child := currNode.getChild(node.label, node.isParam, node.isStar); child == nil {
node.addHanlder(methods, handlerMiddleware{handler: handler, middlewares: middlewares})
node.addHanlder(methods, hm)
currNode.addChild(&node)
} else {
child.addHanlder(methods, handlerMiddleware{handler: handler, middlewares: middlewares})
child.addHanlder(methods, hm)
}
}
}
Expand Down Expand Up @@ -185,6 +191,7 @@ func (n *Node) addHanlder(methods []string, hm handlerMiddleware) {
}
}

// setLabel sets the node's appropriate label.
func (n *Node) setLabel(label string) {
n.label = label
if n.isParam {
Expand Down
4 changes: 3 additions & 1 deletion tree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ func TestNode_addHanlder(t *testing.T) {

assert.PanicsWithValue(
t,
"handler is already registered for method GET and node &{id:0 label: children:[] isParam:false isStar:false handlerMap:map[GET:{handler:<nil> middlewares:[]} POST:{handler:<nil> middlewares:[]}]}.",
"handler is already registered for method GET and node &{id:0 label: children:[] isParam:false isStar:false handlerMap:map[GET:{handler:<nil> middlewares:[] name:} POST:{handler:<nil> middlewares:[] name:}]}.",
func() {
node.addHanlder([]string{http.MethodGet, http.MethodPost}, handlerMiddleware{})
},
Expand Down Expand Up @@ -123,6 +123,7 @@ func TestTree_insertNode(t *testing.T) {
assert.True(t, ok)
assert.True(t, funcsAreEqual(hm.handler, testHandlerFunc))
assert.Nil(t, hm.middlewares)
assert.Equal(t, "/test/path", hm.name)

tree.insertNode("/test", []string{http.MethodPost}, []MiddlewareFunc{testMiddlewareFunc}, testHandlerFunc)

Expand All @@ -140,6 +141,7 @@ func TestTree_insertNode(t *testing.T) {
assert.True(t, ok)
assert.True(t, funcsAreEqual(hm.handler, testHandlerFunc))
assert.Len(t, hm.middlewares, 1)
assert.Equal(t, "/test", hm.name)
}

func TestNode_insert_Panics(t *testing.T) {
Expand Down