Skip to content

Commit

Permalink
store the request context into context.Context
Browse files Browse the repository at this point in the history
  • Loading branch information
xgfone committed Dec 23, 2021
1 parent b43f3f1 commit 1172d77
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
14 changes: 14 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package ship

import (
"bytes"
"context"
"encoding/json"
"encoding/xml"
"fmt"
Expand All @@ -32,6 +33,19 @@ import (
"strings"
)

type reqctx uint8

// GetContext returns the http reqeust context from the context.
func GetContext(ctx context.Context) *Context {
c, _ := ctx.Value(reqctx(255)).(*Context)
return c
}

// SetContext sets the http request context into the context.
func SetContext(ctx context.Context, c *Context) (newctx context.Context) {
return context.WithValue(ctx, reqctx(255), c)
}

// MaxMemoryLimit is the maximum memory.
var MaxMemoryLimit int64 = 32 << 20 // 32MB

Expand Down
19 changes: 19 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,30 @@
package ship

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

func BenchmarkContext(b *testing.B) {
c := NewContext(0, 0)
b.ResetTimer()
b.RunParallel(func(p *testing.PB) {
for p.Next() {
GetContext(SetContext(context.Background(), c))
}
})
}

func TestContext(t *testing.T) {
c := NewContext(0, 0)
nc := GetContext(SetContext(context.Background(), c))
if nc != c {
t.Errorf("unexpect the context")
}
}

func TestContextBindQuery(t *testing.T) {
type V struct {
A string `query:"a" default:"xyz"`
Expand Down

0 comments on commit 1172d77

Please sign in to comment.