Skip to content

Commit

Permalink
feat: rename context to cTx in to avoid the inconvenient rename of co…
Browse files Browse the repository at this point in the history
…ntext package to netcontext
  • Loading branch information
tigerwill90 committed Jun 25, 2024
1 parent 07edbe8 commit 4a94cfe
Show file tree
Hide file tree
Showing 8 changed files with 57 additions and 57 deletions.
64 changes: 32 additions & 32 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
package fox

import (
netcontext "context"
"context"
"fmt"
"io"
"net"
Expand Down Expand Up @@ -76,8 +76,8 @@ type Context interface {
Reset(w ResponseWriter, r *http.Request)
}

// context holds request-related information and allows interaction with the ResponseWriter.
type context struct {
// cTx holds request-related information and allows interaction with the ResponseWriter.
type cTx struct {
w ResponseWriter
req *http.Request
params *Params
Expand All @@ -93,7 +93,7 @@ type context struct {
}

// Reset resets the Context to its initial state, attaching the provided ResponseWriter and http.Request.
func (c *context) Reset(w ResponseWriter, r *http.Request) {
func (c *cTx) Reset(w ResponseWriter, r *http.Request) {
c.req = r
c.w = w
c.path = ""
Expand All @@ -104,7 +104,7 @@ func (c *context) Reset(w ResponseWriter, r *http.Request) {
// reset resets the Context to its initial state, attaching the provided http.ResponseWriter and http.Request.
// Caution: You should always pass the original http.ResponseWriter to this method, not the ResponseWriter itself, to
// avoid wrapping the ResponseWriter within itself. Use wisely!
func (c *context) reset(w http.ResponseWriter, r *http.Request) {
func (c *cTx) reset(w http.ResponseWriter, r *http.Request) {
c.rec.reset(w)
c.req = r
c.w = &c.rec
Expand All @@ -113,7 +113,7 @@ func (c *context) reset(w http.ResponseWriter, r *http.Request) {
*c.params = (*c.params)[:0]
}

func (c *context) resetNil() {
func (c *cTx) resetNil() {
c.req = nil
c.w = nil
c.path = ""
Expand All @@ -122,27 +122,27 @@ func (c *context) resetNil() {
}

// Request returns the *http.Request.
func (c *context) Request() *http.Request {
func (c *cTx) Request() *http.Request {
return c.req
}

// SetRequest sets the *http.Request.
func (c *context) SetRequest(r *http.Request) {
func (c *cTx) SetRequest(r *http.Request) {
c.req = r
}

// Writer returns the ResponseWriter.
func (c *context) Writer() ResponseWriter {
func (c *cTx) Writer() ResponseWriter {
return c.w
}

// SetWriter sets the ResponseWriter.
func (c *context) SetWriter(w ResponseWriter) {
func (c *cTx) SetWriter(w ResponseWriter) {
c.w = w
}

// RemoteIP parses the IP from Request.RemoteAddr, normalizes and returns a net.IP.
func (c *context) RemoteIP() net.IP {
func (c *cTx) RemoteIP() net.IP {
ip, _, err := net.SplitHostPort(strings.TrimSpace(c.req.RemoteAddr))
if err != nil {
return nil
Expand All @@ -152,13 +152,13 @@ func (c *context) RemoteIP() net.IP {

// Params returns a Params slice containing the matched
// wildcard parameters.
func (c *context) Params() Params {
func (c *cTx) Params() Params {
return *c.params
}

// Param retrieve a matching wildcard segment by name.
// It's a helper for c.Params.Get(name).
func (c *context) Param(name string) string {
func (c *cTx) Param(name string) string {
for _, p := range c.Params() {
if p.Key == name {
return p.Value
Expand All @@ -170,33 +170,33 @@ func (c *context) Param(name string) string {
// QueryParams parses RawQuery and returns the corresponding values.
// It's a helper for c.Request.URL.Query(). Note that the parsed
// result is cached.
func (c *context) QueryParams() url.Values {
func (c *cTx) QueryParams() url.Values {
return c.getQueries()
}

// QueryParam returns the first value associated with the given key.
// It's a helper for c.QueryParams().Get(name).
func (c *context) QueryParam(name string) string {
func (c *cTx) QueryParam(name string) string {
return c.getQueries().Get(name)
}

// SetHeader sets the response header for the given key to the specified value.
func (c *context) SetHeader(key, value string) {
func (c *cTx) SetHeader(key, value string) {
c.w.Header().Set(key, value)
}

// Header retrieves the value of the request header for the given key.
func (c *context) Header(key string) string {
func (c *cTx) Header(key string) string {
return c.req.Header.Get(key)
}

// Path returns the registered path for the handler.
func (c *context) Path() string {
func (c *cTx) Path() string {
return c.path
}

// String sends a formatted string with the specified status code.
func (c *context) String(code int, format string, values ...any) (err error) {
func (c *cTx) String(code int, format string, values ...any) (err error) {
if c.w.Header().Get(HeaderContentType) == "" {
c.w.Header().Set(HeaderContentType, MIMETextPlainCharsetUTF8)
}
Expand All @@ -206,23 +206,23 @@ func (c *context) String(code int, format string, values ...any) (err error) {
}

// Blob sends a byte slice with the specified status code and content type.
func (c *context) Blob(code int, contentType string, buf []byte) (err error) {
func (c *cTx) Blob(code int, contentType string, buf []byte) (err error) {
c.w.Header().Set(HeaderContentType, contentType)
c.w.WriteHeader(code)
_, err = c.w.Write(buf)
return
}

// Stream sends data from an io.Reader with the specified status code and content type.
func (c *context) Stream(code int, contentType string, r io.Reader) (err error) {
func (c *cTx) Stream(code int, contentType string, r io.Reader) (err error) {
c.w.Header().Set(HeaderContentType, contentType)
c.w.WriteHeader(code)
_, err = io.Copy(c.w, r)
return
}

// Redirect sends an HTTP redirect response with the given status code and URL.
func (c *context) Redirect(code int, url string) error {
func (c *cTx) Redirect(code int, url string) error {
if code < http.StatusMultipleChoices || code > http.StatusPermanentRedirect {
return ErrInvalidRedirectCode
}
Expand All @@ -231,19 +231,19 @@ func (c *context) Redirect(code int, url string) error {
}

// Tree is a local copy of the Tree in use to serve the request.
func (c *context) Tree() *Tree {
func (c *cTx) Tree() *Tree {
return c.tree
}

// Fox returns the Router instance.
func (c *context) Fox() *Router {
func (c *cTx) Fox() *Router {
return c.fox
}

// Clone returns a copy of the Context that is safe to use after the HandlerFunc returns.
// Any attempt to write on the ResponseWriter will panic with the error ErrDiscardedResponseWriter.
func (c *context) Clone() Context {
cp := context{
func (c *cTx) Clone() Context {
cp := cTx{
rec: c.rec,
req: c.req.Clone(c.req.Context()),
fox: c.fox,
Expand All @@ -264,8 +264,8 @@ func (c *context) Clone() Context {
// copy process. The returned ContextCloser must be closed once no longer needed.
// This functionality is particularly beneficial for middlewares that need to wrap
// their custom ResponseWriter while preserving the state of the original Context.
func (c *context) CloneWith(w ResponseWriter, r *http.Request) ContextCloser {
cp := c.tree.ctx.Get().(*context)
func (c *cTx) CloneWith(w ResponseWriter, r *http.Request) ContextCloser {
cp := c.tree.ctx.Get().(*cTx)
cp.req = r
cp.w = w
cp.path = c.path
Expand All @@ -282,7 +282,7 @@ func (c *context) CloneWith(w ResponseWriter, r *http.Request) ContextCloser {
}

// Close releases the context to be reused later.
func (c *context) Close() {
func (c *cTx) Close() {
// Put back the context, if not extended more than max params or max depth, allowing
// the slice to naturally grow within the constraint.
if cap(*c.params) > int(c.tree.maxParams.Load()) || cap(*c.skipNds) > int(c.tree.maxDepth.Load()) {
Expand All @@ -291,7 +291,7 @@ func (c *context) Close() {
c.tree.ctx.Put(c)
}

func (c *context) getQueries() url.Values {
func (c *cTx) getQueries() url.Values {
if c.cachedQuery == nil {
if c.req != nil {
c.cachedQuery = c.req.URL.Query()
Expand All @@ -307,7 +307,7 @@ func (c *context) getQueries() url.Values {
func WrapF(f http.HandlerFunc) HandlerFunc {
return func(c Context) {
if len(c.Params()) > 0 {
ctx := netcontext.WithValue(c.Request().Context(), paramsKey, c.Params().Clone())
ctx := context.WithValue(c.Request().Context(), paramsKey, c.Params().Clone())
f.ServeHTTP(c.Writer(), c.Request().WithContext(ctx))
return
}
Expand All @@ -321,7 +321,7 @@ func WrapF(f http.HandlerFunc) HandlerFunc {
func WrapH(h http.Handler) HandlerFunc {
return func(c Context) {
if len(c.Params()) > 0 {
ctx := netcontext.WithValue(c.Request().Context(), paramsKey, c.Params().Clone())
ctx := context.WithValue(c.Request().Context(), paramsKey, c.Params().Clone())
h.ServeHTTP(c.Writer(), c.Request().WithContext(ctx))
return
}
Expand Down
4 changes: 2 additions & 2 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ func TestWrapF(t *testing.T) {
params := make(Params, 0)
if tc.params != nil {
params = tc.params.Clone()
c.(*context).params = &params
c.(*cTx).params = &params
}

WrapF(tc.handler(params))(c)
Expand Down Expand Up @@ -351,7 +351,7 @@ func TestWrapH(t *testing.T) {
params := make(Params, 0)
if tc.params != nil {
params = tc.params.Clone()
c.(*context).params = &params
c.(*cTx).params = &params
}

WrapH(tc.handler(params))(c)
Expand Down
2 changes: 1 addition & 1 deletion fox.go
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ func (fox *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}

tree := fox.tree.Load()
c := tree.ctx.Get().(*context)
c := tree.ctx.Get().(*cTx)
c.reset(w, r)

nds := *tree.nodes.Load()
Expand Down
8 changes: 4 additions & 4 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func NewTestContextOnly(fox *Router, w http.ResponseWriter, r *http.Request) Con
return newTextContextOnly(fox, w, r)
}

func newTextContextOnly(fox *Router, w http.ResponseWriter, r *http.Request) *context {
func newTextContextOnly(fox *Router, w http.ResponseWriter, r *http.Request) *cTx {
c := fox.Tree().allocateContext()
c.resetNil()
c.req = r
Expand All @@ -30,7 +30,7 @@ func newTextContextOnly(fox *Router, w http.ResponseWriter, r *http.Request) *co
return c
}

func newTestContextTree(t *Tree) *context {
func newTestContextTree(t *Tree) *cTx {
c := t.allocateContext()
c.resetNil()
return c
Expand All @@ -44,9 +44,9 @@ func newResponseWriter(w http.ResponseWriter) ResponseWriter {
}
}

func unwrapContext(t *testing.T, c Context) *context {
func unwrapContext(t *testing.T, c Context) *cTx {
t.Helper()
cc, ok := c.(*context)
cc, ok := c.(*cTx)
if !ok {
t.Fatal("unable to unwrap context")
}
Expand Down
8 changes: 4 additions & 4 deletions internal/slogpretty/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
package slogpretty

import (
netcontext "context"
"context"
"fmt"
"github.com/tigerwill90/fox/internal/ansi"
"io"
Expand Down Expand Up @@ -58,11 +58,11 @@ type LogHandler struct {
Goa []GroupOrAttrs
}

func (h *LogHandler) Enabled(_ netcontext.Context, level slog.Level) bool {
func (h *LogHandler) Enabled(_ context.Context, level slog.Level) bool {
return level >= h.Lvl.Level()
}

func (h *LogHandler) Handle(_ netcontext.Context, record slog.Record) error {
func (h *LogHandler) Handle(_ context.Context, record slog.Record) error {
bufp := logBufPool.Get().(*[]byte)
buf := *bufp

Expand Down Expand Up @@ -222,8 +222,8 @@ func appendAttr(level slog.Level, buf []byte, attr slog.Attr) []byte {
}

type lockedWriter struct {
sync.Mutex
w io.Writer
sync.Mutex
}

func (w *lockedWriter) Write(p []byte) (n int, err error) {
Expand Down
6 changes: 3 additions & 3 deletions params.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

package fox

import netcontext "context"
import "context"

type ctxKey struct{}

Expand Down Expand Up @@ -46,9 +46,9 @@ func (p Params) Clone() Params {
return cloned
}

// ParamsFromContext is a helper to retrieve params from context when a http.Handler
// ParamsFromContext is a helper to retrieve params from context.Context when a http.Handler
// is registered using WrapF or WrapH.
func ParamsFromContext(ctx netcontext.Context) Params {
func ParamsFromContext(ctx context.Context) Params {
p, _ := ctx.Value(paramsKey).(Params)
return p
}
10 changes: 5 additions & 5 deletions params_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
package fox

import (
netcontext "context"
"context"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -67,25 +67,25 @@ func TestParamsFromContext(t *testing.T) {

cases := []struct {
name string
ctx netcontext.Context
ctx context.Context
expectedParams Params
}{
{
name: "empty context",
ctx: netcontext.Background(),
ctx: context.Background(),
expectedParams: nil,
},
{
name: "context with params",
ctx: func() netcontext.Context {
ctx: func() context.Context {
params := make(Params, 0, 2)
params = append(params,
Param{
Key: "foo",
Value: "bar",
},
)
return netcontext.WithValue(netcontext.Background(), paramsKey, params)
return context.WithValue(context.Background(), paramsKey, params)
}(),
expectedParams: func() Params {
params := make(Params, 0, 2)
Expand Down
Loading

0 comments on commit 4a94cfe

Please sign in to comment.