prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
der
import (
"github.com/gofiber/utils/v2"
"github.com/valyala/fasthttp"
)
// QueryBinding is the query binder for query request body.
type QueryBinding struct {
EnableSplitting bool
}
// Name returns the binding name.
func (*QueryBinding) Name() string {
return bindingQuery
}
// Bind parses the request query a... | l)
if err := formatBindData(b.Name(), out, data, k, v, b.EnableSplitting, true); err != nil {
return err
}
}
return parse(b.Name(), out, data)
}
// Reset resets the QueryBinding binder.
func (b *QueryBinding) Reset() {
b.EnableSplitting = false | utils.UnsafeString(key)
v := utils.UnsafeString(va | {
"filepath": "binder/query.go",
"language": "go",
"file_size": 834,
"cut_index": 523,
"middle_length": 52
} |
mport (
"github.com/gofiber/utils/v2"
"github.com/valyala/fasthttp"
)
// RespHeaderBinding is the respHeader binder for response header.
type RespHeaderBinding struct {
EnableSplitting bool
}
// Name returns the binding name.
func (*RespHeaderBinding) Name() string {
return bindingRespHeader
}
// Bind parses the... | eString(val)
if err := formatBindData(b.Name(), out, data, k, v, b.EnableSplitting, false); err != nil {
return err
}
}
return parse(b.Name(), out, data)
}
// Reset resets the RespHeaderBinding binder.
func (b *RespHeaderBinding) Reset() {
b.En | {
k := utils.UnsafeString(key)
v := utils.Unsaf | {
"filepath": "binder/resp_header.go",
"language": "go",
"file_size": 861,
"cut_index": 529,
"middle_length": 52
} |
e binder
import (
"errors"
"github.com/gofiber/utils/v2"
)
// CBORBinding is the CBOR binder for CBOR request body.
type CBORBinding struct {
CBORDecoder utils.CBORUnmarshal
}
// Name returns the binding name.
func (*CBORBinding) Name() string {
return "cbor"
}
// Bind parses the request body as CBOR and retur... | iber.io/next/guide/advance-format#cbor")
// UnimplementedCborMarshal returns an error to signal that a CBOR marshaler
// must be configured before CBOR support can be used.
func UnimplementedCborMarshal(_ any) ([]byte, error) {
return nil, ErrUnimplement | er = nil
}
// ErrUnimplementedCBOR signals that CBOR support must be explicitly configured
// before it can be used.
var ErrUnimplementedCBOR = errors.New("binder: must explicitly set up CBOR, please check docs: https://docs.gof | {
"filepath": "binder/cbor.go",
"language": "go",
"file_size": 1237,
"cut_index": 518,
"middle_length": 229
} |
"testing"
"github.com/stretchr/testify/require"
)
func Test_URIBinding_Bind(t *testing.T) {
t.Parallel()
b := &URIBinding{}
require.Equal(t, "uri", b.Name())
type User struct {
Name string `uri:"name"`
Posts []string `uri:"posts"`
Age int `uri:"age"`
}
var user User
paramsKey := []string{"... | }, user.Posts)
b.Reset()
}
func Benchmark_URIBinding_Bind(b *testing.B) {
b.ReportAllocs()
binder := &URIBinding{}
type User struct {
Name string `uri:"name"`
Posts []string `uri:"posts"`
Age int `uri:"age"`
}
var user User
para | urn paramsVals[i]
}
}
return ""
}
err := b.Bind(paramsKey, paramsFunc, &user)
require.NoError(t, err)
require.Equal(t, "john", user.Name)
require.Equal(t, 42, user.Age)
require.Equal(t, []string{"post1,post2,post3" | {
"filepath": "binder/uri_test.go",
"language": "go",
"file_size": 1519,
"cut_index": 537,
"middle_length": 229
} |
uire"
)
func Test_ExponentialBackoff_Retry(t *testing.T) {
t.Parallel()
tests := []struct {
expErr error
expBackoff *ExponentialBackoff
f func() error
name string
}{
{
name: "With default values - successful",
expBackoff: NewExponentialBackoff(),
f: func() error {
ret... | 00 * time.Millisecond,
Multiplier: 2.0,
MaxRetryCount: 5,
},
f: func() error {
return errors.New("failed function")
},
expErr: errors.New("failed function"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testi | r: 2.0,
MaxRetryCount: 5,
},
f: func() error {
return nil
},
},
{
name: "Unsuccessful function",
expBackoff: &ExponentialBackoff{
InitialInterval: 2 * time.Millisecond,
MaxBackoffTime: 1 | {
"filepath": "addon/retry/exponential_backoff_test.go",
"language": "go",
"file_size": 4142,
"cut_index": 614,
"middle_length": 229
} |
, fasthttp.HostClient, or fasthttp.LBClient implementations.
//
// Settings configured on the client are shared across every request and may be
// overridden per request when needed.
// Client is safe for concurrent request execution after configuration is
// complete. Concurrent configuration changes require external ... | g *RetryConfig
baseURL string
userAgent string
referer string
userRequestHooks []RequestHook
builtinRequestHooks []RequestHook
userResponseHooks []ResponseHook
builtinResponseHooks []ResponseHook | ls.JSONMarshal
jsonUnmarshal utils.JSONUnmarshal
xmlMarshal utils.XMLMarshal
xmlUnmarshal utils.XMLUnmarshal
cborMarshal utils.CBORMarshal
cborUnmarshal utils.CBORUnmarshal
cookieJar *CookieJar
retryConfi | {
"filepath": "client/client.go",
"language": "go",
"file_size": 24581,
"cut_index": 1331,
"middle_length": 229
} |
hamaton/msgpack/v3"
"github.com/stretchr/testify/require"
)
func Test_Msgpack_Binding_Bind(t *testing.T) {
t.Parallel()
b := &MsgPackBinding{
MsgPackDecoder: msgpack.Unmarshal,
}
require.Equal(t, "msgpack", b.Name())
type Post struct {
Title string `msgpack:"title"`
}
type User struct {
Name string `... | "john", user.Name)
require.Equal(t, 42, user.Age)
require.Len(t, user.Posts, 3)
require.Equal(t, "post1", user.Posts[0].Title)
require.Equal(t, "post2", user.Posts[1].Title)
require.Equal(t, "post3", user.Posts[2].Title)
b.Reset()
require.Nil(t, b. | []map[string]any{
{"title": "post1"},
{"title": "post2"},
{"title": "post3"},
},
}
data, err := msgpack.Marshal(input)
require.NoError(t, err)
err = b.Bind(data, &user)
require.NoError(t, err)
require.Equal(t, | {
"filepath": "binder/msgpack_test.go",
"language": "go",
"file_size": 2447,
"cut_index": 563,
"middle_length": 229
} |
&CookieJar{}
},
}
// AcquireCookieJar returns an empty CookieJar object from the pool.
func AcquireCookieJar() *CookieJar {
jar, ok := cookieJarPool.Get().(*CookieJar)
if !ok {
panic(errCookieJarTypeAssertion)
}
return jar
}
// ReleaseCookieJar returns a CookieJar object to the pool.
func ReleaseCookieJar(c ... |
// accepted Domain attribute.
// If release logic is re-enabled for these entries, iterate as storedCookie
// values and call fasthttp.ReleaseCookie(stored.cookie) on the wrapped cookie.
hostCookies map[string][]storedCookie
mu sync.Mutex
}
| ently with other methods, and the jar must not be used after Release.
type CookieJar struct {
// hostCookies stores wrapped cookies keyed by storage scope:
// host-only cookies use the request host, while domain cookies use the | {
"filepath": "client/cookiejar.go",
"language": "go",
"file_size": 12177,
"cut_index": 921,
"middle_length": 229
} |
[]struct {
name string
want string
args args
}{
{
name: "do anything",
args: args{
addr: "example.com:1234",
},
want: "example.com:1234",
},
{
name: "add 80 port",
args: args{
addr: "example.com",
},
want: "example.com:80",
},
{
name: "add 443 port",
args: args{
... | endString(c.Hostname())
})
app.Get("/return-error", func(_ fiber.Ctx) error {
return errors.New("the request is error")
})
app.Get("/redirect", func(c fiber.Ctx) error {
return c.Redirect().Status(fiber.StatusFound).To("/normal")
})
app.Get("/ | , addMissingPort(tt.args.addr, tt.args.isTLS))
})
}
}
func Test_Exec_Func(t *testing.T) {
t.Parallel()
ln := fasthttputil.NewInmemoryListener()
app := fiber.New()
app.Get("/normal", func(c fiber.Ctx) error {
return c.S | {
"filepath": "client/core_test.go",
"language": "go",
"file_size": 14945,
"cut_index": 921,
"middle_length": 229
} |
cationJSON = "application/json"
applicationCBOR = "application/cbor"
applicationXML = "application/xml"
applicationForm = "application/x-www-form-urlencoded"
multipartFormData = "multipart/form-data"
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
)
// unsafeRandString ret... | make([]byte, n)
buf := make([]byte, n)
// Read n raw bytes in one shot
if _, err := rand.Read(buf); err != nil {
return "", fmt.Errorf("rand.Read failed: %w", err)
}
for i, b := range buf {
// Reject values ≥ maxLength
for b >= maxLength {
| gest multiple of inputLength ≤ 256 to avoid modulo bias.
// Any byte ≥ max will be rejected and re‑read.
maxLength := byte(256 - (256 % int(inputLength))) //nolint:gosec // G115: integer overflow conversion int -> byte
out := | {
"filepath": "client/hooks.go",
"language": "go",
"file_size": 9354,
"cut_index": 921,
"middle_length": 229
} |
llel()
got, err := unsafeRandString(32)
require.NoError(t, err)
for i := 0; i < len(got); i++ {
require.Contains(t, letterBytes, string(got[i]))
}
})
}
func Test_Parser_Request_URL(t *testing.T) {
t.Parallel()
t.Run("client baseurl should be set", func(t *testing.T) {
t.Parallel()
client := New().Se... | rror(t, err)
require.Equal(t, "http://example.com/api", req.RawRequest.URI().String())
})
t.Run("the request url will override baseurl with protocol", func(t *testing.T) {
t.Parallel()
client := New().SetBaseURL("http://example.com/api")
req := | quest.URI().String())
})
t.Run("request url should be set", func(t *testing.T) {
t.Parallel()
client := New()
req := AcquireRequest().SetURL("http://example.com/api")
err := parserRequestURL(client, req)
require.NoE | {
"filepath": "client/hooks_test.go",
"language": "go",
"file_size": 20839,
"cut_index": 1331,
"middle_length": 229
} |
x.Value(key))
ctx = context.WithValue(ctx, key, "string")
req.SetContext(ctx)
ctx = req.Context()
v, ok := ctx.Value(key).(string)
require.True(t, ok)
require.Equal(t, "string", v)
}
func Test_Request_Header(t *testing.T) {
t.Parallel()
t.Run("add header", func(t *testing.T) {
t.Parallel()
req := Acquir... | )
})
t.Run("add headers", func(t *testing.T) {
t.Parallel()
req := AcquireRequest()
req.SetHeader("foo", "bar").
AddHeaders(map[string][]string{
"foo": {"fiber", "buaa"},
"bar": {"foo"},
})
res := req.Header("foo")
require.Len(t | )
t.Run("set header", func(t *testing.T) {
t.Parallel()
req := AcquireRequest()
req.AddHeader("foo", "bar").SetHeader("foo", "fiber")
res := req.Header("foo")
require.Len(t, res, 1)
require.Equal(t, "fiber", res[0] | {
"filepath": "client/request_test.go",
"language": "go",
"file_size": 41271,
"cut_index": 2151,
"middle_length": 229
} |
"http://example")
require.NoError(t, err)
require.Equal(t, "OK", resp.Status())
resp.Close()
})
t.Run("fail", func(t *testing.T) {
t.Parallel()
server := setupApp()
defer server.stop()
client := New().SetDial(server.dial())
resp, err := AcquireRequest().
SetClient(client).
Get("http://examp... | tus(407)
})
})
return server
}
t.Run("success", func(t *testing.T) {
t.Parallel()
server := setupApp()
defer server.stop()
client := New().SetDial(server.dial())
resp, err := AcquireRequest().
SetClient(client).
Get("http://ex | upApp := func() *testServer {
server := startTestServer(t, func(app *fiber.App) {
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("foo")
})
app.Get("/fail", func(c fiber.Ctx) error {
return c.SendSta | {
"filepath": "client/response_test.go",
"language": "go",
"file_size": 21439,
"cut_index": 1331,
"middle_length": 229
} |
nt *fasthttp.LBClient
}
func (l *lbBalancingClient) DoDeadline(req *fasthttp.Request, resp *fasthttp.Response, deadline time.Time) error {
if l.client == nil {
return nil
}
return l.client.DoDeadline(req, resp, deadline)
}
func (*lbBalancingClient) PendingRequests() int { return 0 }
func (l *lbBalancingClient) ... | (s.calls) == 0 {
resp.Reset()
resp.Header.SetStatusCode(fasthttp.StatusOK)
return nil
}
call := s.calls[0]
s.calls = s.calls[1:]
resp.Reset()
if call.status != nil {
resp.Header.SetStatusCode(*call.status)
}
if call.location != nil {
res | ring) *string { return &v }
type stubRedirectClient struct {
calls []stubRedirectCall
callCount int
}
func (s *stubRedirectClient) Do(req *fasthttp.Request, resp *fasthttp.Response) error {
_ = req
s.callCount++
if len | {
"filepath": "client/transport_test.go",
"language": "go",
"file_size": 16928,
"cut_index": 921,
"middle_length": 229
} |
ag = "${"
endTag = "}"
paramSeparator = ":"
)
// Buffer is the render buffer exposed to template functions.
// The template renderer only requires Write, WriteByte, and WriteString, but
// the wider bytebufferpool-compatible surface is kept so existing custom
// logger tags that use methods such as Len... | , D any] func(output Buffer, ctx C, data *D, extraParam string) (int, error)
// Template is a precompiled log template.
type Template[C, D any] struct {
fixedParts [][]byte
funcChain []Func[C, D]
}
// Build parses format once and returns a reusable te | nt64, error)
Bytes() []byte
Write(p []byte) (int, error)
WriteByte(c byte) error
WriteString(s string) (int, error)
Set(p []byte)
SetString(s string)
String() string
}
// Func renders one dynamic template tag.
type Func[C | {
"filepath": "internal/logtemplate/template.go",
"language": "go",
"file_size": 4051,
"cut_index": 614,
"middle_length": 229
} |
kage redact provides common helpers for masking sensitive values in log
// output. It is internal because the redaction policy is not part of Fiber's
// public API.
package redact
const (
// MinLength is the inclusive lower bound on input length for which the
// redacted form keeps a leading clear-text prefix. Value... | returns a redacted form of value. Empty input is returned unchanged.
// Inputs shorter than MinLength are fully masked. Inputs at least MinLength
// long return the leading PrefixLength bytes followed by Mask. Operations are
// byte-wise; callers must not | f leading bytes kept when the input is at
// least MinLength long.
PrefixLength = 4
// Mask is appended after the visible prefix (or returned alone when the
// input is too short to keep a prefix).
Mask = "****"
)
// Prefix | {
"filepath": "internal/redact/redact.go",
"language": "go",
"file_size": 1230,
"cut_index": 518,
"middle_length": 229
} |
"time"
)
// Config defines the config for addon.
type Config struct {
// InitialInterval defines the initial time interval for backoff algorithm.
//
// Optional. Default: 1 * time.Second
InitialInterval time.Duration
// MaxBackoffTime defines maximum time duration for backoff algorithm. When
// the algorithm is... | urrent waiting time.
//
// Optional. Default: 1 * time.Second
currentInterval time.Duration
}
// DefaultConfig is the default config for retry.
var DefaultConfig = Config{
InitialInterval: 1 * time.Second,
MaxBackoffTime: 32 * time.Second,
Multipli | he backoff algorithm.
//
// Optional. Default: 2.0
Multiplier float64
// MaxRetryCount defines maximum retry count for the backoff algorithm.
//
// Optional. Default: 10
MaxRetryCount int
// currentInterval tracks the c | {
"filepath": "addon/retry/config.go",
"language": "go",
"file_size": 1690,
"cut_index": 537,
"middle_length": 229
} |
er/fiber/v3"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/valyala/fasthttp/fasthttputil"
)
type testServer struct {
app *fiber.App
ch chan struct{}
ln *fasthttputil.InmemoryListener
tb testing.TB
}
func startTestServer(tb testing.TB, beforeStarting func(app *fiber.A... | ch: ch,
ln: ln,
tb: tb,
}
}
func (ts *testServer) stop() {
ts.tb.Helper()
if err := ts.app.Shutdown(); err != nil {
ts.tb.Fatal(err)
}
select {
case <-ts.ch:
case <-time.After(time.Second):
ts.tb.Fatalf("timeout when waiting for server | = nil {
beforeStarting(app)
}
ch := make(chan struct{})
go func() {
err := app.Listener(ln, fiber.ListenConfig{DisableStartupMessage: true})
assert.NoError(tb, err)
close(ch)
}()
return &testServer{
app: app,
| {
"filepath": "client/helper_test.go",
"language": "go",
"file_size": 3374,
"cut_index": 614,
"middle_length": 229
} |
"runtime"
"runtime/metrics"
"strconv"
"testing"
)
// BenchmarkRequestHeapScan measures how much heap memory the GC needs to scan
// when a batch of requests is created and released.
func BenchmarkRequestHeapScan(b *testing.B) {
samples := []metrics.Sample{
{Name: "/gc/scan/heap:bytes"},
{Name: "/gc/scan/total... | ()
b.StartTimer()
for j := range reqs {
req := AcquireRequest()
req.SetHeader("X-Benchmark", "value")
req.SetCookie("session", strconv.Itoa(j))
req.SetPathParam("id", strconv.Itoa(j))
req.SetParam("page", strconv.Itoa(j))
reqs[j] = r |
// revive:disable-next-line:call-to-gc // Ensure consistent heap state before measuring scan metrics
runtime.GC()
metrics.Read(samples)
startScanHeap := samples[0].Value.Uint64()
startScanAll := samples[1].Value.Uint64 | {
"filepath": "client/request_bench_test.go",
"language": "go",
"file_size": 1529,
"cut_index": 537,
"middle_length": 229
} |
onst defaultRedirectLimit = 16
var (
// Pre-allocated byte slice for http/https scheme comparison
httpScheme = []byte("http")
httpsScheme = []byte("https")
)
// httpClientTransport unifies the operations exposed by the Fiber client across
// the fasthttp.Client, fasthttp.HostClient, and fasthttp.LBClient adapters... | loseIdleConnections()
TLSConfig() *tls.Config
SetTLSConfig(config *tls.Config)
SetDial(dial fasthttp.DialFunc)
Client() any
StreamResponseBody() bool
SetStreamResponseBody(enable bool)
}
// standardClientTransport adapts fasthttp.Client to the httpC | , resp *fasthttp.Response, timeout time.Duration) error
DoDeadline(req *fasthttp.Request, resp *fasthttp.Response, deadline time.Time) error
DoRedirects(req *fasthttp.Request, resp *fasthttp.Response, maxRedirects int) error
C | {
"filepath": "client/transport.go",
"language": "go",
"file_size": 11572,
"cut_index": 921,
"middle_length": 229
} |
ute(t *testing.T) {
t.Parallel()
tmpl, err := Build[string, testData]("a ${tag} ${param:name} z", map[string]Func[string, testData]{
"tag": func(output Buffer, ctx string, data *testData, _ string) (int, error) {
return output.WriteString(ctx + data.value)
},
"param:": func(output Buffer, _ string, _ *testD... | stData]
buf := bytebufferpool.Get()
defer bytebufferpool.Put(buf)
require.NoError(t, tmpl.Execute(buf, "ctx", &testData{}))
require.Equal(t, 0, buf.Len())
parts, funcs := tmpl.Chains()
require.Nil(t, parts)
require.Nil(t, funcs)
}
func Test_Temp | ute(buf, "ctx-", &testData{value: "data"})
require.NoError(t, err)
require.Equal(t, "a ctx-data name z", buf.String())
}
func Test_Template_NilTemplateExecuteIsNoop(t *testing.T) {
t.Parallel()
var tmpl *Template[string, te | {
"filepath": "internal/logtemplate/template_test.go",
"language": "go",
"file_size": 5586,
"cut_index": 716,
"middle_length": 229
} |
ored in the request.
body any
header Header
params QueryParam
cookies Cookie
path PathParam
client *Client
formData FormData
RawRequest *fasthttp.Request
url string
method string
userAgent string
boundary string
referer string
files []*File
timeout time.Duration
m... | set in the Request.
func (r *Request) URL() string {
return r.url
}
// SetURL sets the URL for the Request.
func (r *Request) SetURL(url string) *Request {
r.url = url
return r
}
// Client returns the Client instance associated with this Request.
func | od sets the HTTP method for the Request.
// It is recommended to use the specialized methods (e.g., Get, Post) instead.
func (r *Request) SetMethod(method string) *Request {
r.method = method
return r
}
// URL returns the URL | {
"filepath": "client/request.go",
"language": "go",
"file_size": 28384,
"cut_index": 1331,
"middle_length": 229
} |
e logtemplate
import (
"errors"
"strconv"
)
// ErrUnknownTag indicates that the template references a tag that has no
// registered renderer. The format may be a bare ${tag} or a parametric
// ${tag:param}; in both cases the unmatched name is reported via
// UnknownTagError so callers can extract it programmaticall... | a bare tag was
// referenced but a parametric base of the same name is registered.
type UnknownTagError struct {
Tag string
Param string
Hint string
}
func (e *UnknownTagError) Error() string {
msg := ErrUnknownTag.Error() + ": " + strconv.Quote(e | ny parametric suffix
// (without the surrounding "${" / "}"). Param is the parameter portion when
// the tag was parametric, or the empty string for bare tags. Hint is an
// optional human-readable suggestion — currently set when | {
"filepath": "internal/logtemplate/errors.go",
"language": "go",
"file_size": 1142,
"cut_index": 518,
"middle_length": 229
} |
oding overhead. Unlike the standard storage interface,
// this storage works directly with Go types for maximum speed.
//
// # Safety Considerations
//
// This storage automatically performs defensive copying for:
// - String keys: Copied to prevent corruption from pooled buffers
// - []byte values: Copied on both ... | age memory
import (
"sync"
"time"
"github.com/gofiber/utils/v2"
)
// Storage stores arbitrary values in memory for use in tests and benchmarks.
// Storage is safe for concurrent use.
type Storage struct {
data map[string]item // data
mu sync.RWMu | es,
// callers are responsible for not mutating the underlying data.
//
// This storage is primarily used internally by middleware for performance-
// critical operations where the stored data types are known and controlled.
pack | {
"filepath": "internal/memory/memory.go",
"language": "go",
"file_size": 3781,
"cut_index": 614,
"middle_length": 229
} |
Package loggertest provides shared helpers for the middleware ctx-logger
// integration tests. The helpers consolidate the SetOutput / SetContextTemplate
// / cleanup boilerplate that would otherwise be duplicated across every
// middleware that registers a context tag.
package loggertest
import (
"bytes"
"os"
"tes... | oss tests.
func CaptureContextLog(tb testing.TB, format string) *bytes.Buffer {
tb.Helper()
var buf bytes.Buffer
fiberlog.SetOutput(&buf)
fiberlog.MustSetContextTemplate(fiberlog.ContextConfig{Format: format})
tb.Cleanup(func() {
fiberlog.MustSetC | , the default
// logger output is restored to os.Stderr and the context template is cleared.
//
// Tests that use this helper must NOT call t.Parallel() because the helper
// mutates package-global default-logger state shared acr | {
"filepath": "internal/loggertest/loggertest.go",
"language": "go",
"file_size": 1093,
"cut_index": 515,
"middle_length": 229
} |
tWithContext(t *testing.T) {
t.Parallel()
var (
testStore = New()
key = "john"
val = []byte("doe")
)
ctx, cancel := context.WithCancel(context.Background())
cancel()
err := testStore.SetWithContext(ctx, key, val, 0)
require.ErrorIs(t, err, context.Canceled)
keys, err := testStore.Keys()
re... | ory_Get(t *testing.T) {
t.Parallel()
var (
testStore = New()
key = "john"
val = []byte("doe")
)
err := testStore.Set(key, val, 0)
require.NoError(t, err)
result, err := testStore.Get(key)
require.NoError(t, err)
require.Equal(t, | )
err := testStore.Set(key, val, 0)
require.NoError(t, err)
err = testStore.Set(key, val, 0)
require.NoError(t, err)
keys, err := testStore.Keys()
require.NoError(t, err)
require.Len(t, keys, 1)
}
func Test_Storage_Mem | {
"filepath": "internal/storage/memory/memory_test.go",
"language": "go",
"file_size": 9548,
"cut_index": 921,
"middle_length": 229
} |
kage contextvalue
import (
"context"
"github.com/valyala/fasthttp"
)
type fiberLocalContext interface {
Locals(key any, value ...any) any
}
type userValueContext interface {
UserValue(key any) any
}
type valueContext interface {
Value(key any) any
}
// Value retrieves a value stored under key from supported ... | val, ok := typed.Value(key).(T)
return val, ok
case valueContext:
val, ok := typed.Value(key).(T)
return val, ok
case fiberLocalContext:
val, ok := typed.Locals(key).(T)
return val, ok
case userValueContext:
val, ok := typed.UserValue(key) | n a context exposes
// multiple accessors so Fiber contexts follow context.Value semantics.
switch typed := ctx.(type) {
case *fasthttp.RequestCtx:
val, ok := typed.UserValue(key).(T)
return val, ok
case context.Context:
| {
"filepath": "internal/contextvalue/contextvalue.go",
"language": "go",
"file_size": 1071,
"cut_index": 515,
"middle_length": 229
} |
"context"
"fmt"
"sync"
"time"
"github.com/gofiber/utils/v2"
)
// Storage provides an in-memory implementation of the storage interface for
// testing purposes.
// Storage is safe for concurrent use, except when callers keep using the live
// map returned by Conn. Access to that map requires external synchronizati... | cfg := configDefault(config...)
// Create storage
store := &Storage{
db: make(map[string]Entry),
gcInterval: cfg.GCInterval,
done: make(chan struct{}),
}
// Start garbage collector
utils.StartTimeStampUpdater()
go store.gc()
| ts expiration.
type Entry struct {
data []byte
// max value is 4294967295 -> Sun Feb 07 2106 06:28:15 GMT+0000
expiry uint32
}
// New creates a new memory storage.
func New(config ...Config) *Storage {
// Set default config
| {
"filepath": "internal/storage/memory/memory.go",
"language": "go",
"file_size": 5609,
"cut_index": 716,
"middle_length": 229
} |
of a request. It provides access to the response data.
type Response struct {
client *Client
request *Request
RawResponse *fasthttp.Response
cookie []*fasthttp.Cookie
}
// setClient sets the client instance in the response. The client object is used by core functionalities.
func (r *Response) setClient(c *... | request.
func (r *Response) StatusCode() int {
return r.RawResponse.StatusCode()
}
// Protocol returns the HTTP protocol used for the request.
func (r *Response) Protocol() string {
return string(r.RawResponse.Header.Protocol())
}
// Header returns th | t = req
}
// Status returns the HTTP status message of the executed request.
func (r *Response) Status() string {
return string(r.RawResponse.Header.StatusMessage())
}
// StatusCode returns the HTTP status code of the executed | {
"filepath": "client/response.go",
"language": "go",
"file_size": 6588,
"cut_index": 716,
"middle_length": 229
} |
"testing"
"time"
"github.com/gofiber/utils/v2"
"github.com/stretchr/testify/require"
)
// go test -run Test_Memory -v -race
func Test_Memory(t *testing.T) {
t.Parallel()
store := New()
var (
key = "john-internal"
val any = []byte("doe")
exp = 1 * time.Second
)
// Set key with value
store.Set(... | t, val, result)
// Delete key
store.Delete(key)
result = store.Get(key)
require.Nil(t, result)
// Reset all keys
store.Set("john-reset", val, 0)
store.Set("doe-reset", val, 0)
store.Reset()
// Check if all keys are deleted
result = store.Get(" | key, val, exp)
require.Eventually(t, func() bool {
return store.Get(key) == nil
}, 3*time.Second, 10*time.Millisecond)
// Set key with value and no expiration
store.Set(key, val, 0)
result = store.Get(key)
require.Equal( | {
"filepath": "internal/memory/memory_test.go",
"language": "go",
"file_size": 1655,
"cut_index": 537,
"middle_length": 229
} |
y a MIT style
// license that can be found in the LICENSE file.
package gin
import (
"crypto/subtle"
"encoding/base64"
"net/http"
"strconv"
"github.com/gin-gonic/gin/internal/bytesconv"
)
// AuthUserKey is the cookie name for user credential in basic auth.
const AuthUserKey = "user"
// AuthProxyUserKey is the... | range a {
if subtle.ConstantTimeCompare(bytesconv.StringToBytes(pair.value), bytesconv.StringToBytes(authValue)) == 1 {
return pair.user, true
}
}
return "", false
}
// BasicAuthForRealm returns a Basic HTTP Authorization middleware. It takes as | p[string]string
type authPair struct {
value string
user string
}
type authPairs []authPair
func (a authPairs) searchCredential(authValue string) (string, bool) {
if authValue == "" {
return "", false
}
for _, pair := | {
"filepath": "auth.go",
"language": "go",
"file_size": 3838,
"cut_index": 614,
"middle_length": 229
} |
y a MIT style
// license that can be found in the LICENSE file.
package gin
import (
"html/template"
"net/http"
"os"
"testing"
)
func BenchmarkOneRoute(B *testing.B) {
router := New()
router.GET("/ping", func(c *Context) {})
runRequest(B, router, http.MethodGet, "/ping")
}
func BenchmarkRecoveryMiddleware(B ... | oggerWithWriter(newMockWriter()))
router.Use(func(c *Context) {})
router.Use(func(c *Context) {})
router.GET("/ping", func(c *Context) {})
runRequest(B, router, http.MethodGet, "/ping")
}
func Benchmark5Params(B *testing.B) {
DefaultWriter = os.Stdou | er := New()
router.Use(LoggerWithWriter(newMockWriter()))
router.GET("/", func(c *Context) {})
runRequest(B, router, http.MethodGet, "/")
}
func BenchmarkManyHandlers(B *testing.B) {
router := New()
router.Use(Recovery(), L | {
"filepath": "benchmarks_test.go",
"language": "go",
"file_size": 3962,
"cut_index": 614,
"middle_length": 229
} |
de == http.StatusForbidden)
})
// Test with HEAD request
t.Run("HEAD request", func(t *testing.T) {
testFile := "testdata/test_file.txt"
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodHead, "/test", nil)
c.File(testFile)
assert.Equal(t, http.Status... | eader.Set("Range", "bytes=0-10")
c.File(testFile)
assert.Equal(t, http.StatusPartialContent, w.Code)
assert.Equal(t, "bytes", w.Header().Get("Accept-Ranges"))
assert.Contains(t, w.Header().Get("Content-Range"), "bytes 0-10")
})
}
func TestConte | quest
t.Run("Range request", func(t *testing.T) {
testFile := "testdata/test_file.txt"
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)
c.Request.H | {
"filepath": "context_test.go",
"language": "go",
"file_size": 112684,
"cut_index": 3790,
"middle_length": 229
} |
y a MIT style
// license that can be found in the LICENSE file.
package gin
import (
"fmt"
"reflect"
"strings"
"github.com/gin-gonic/gin/codec/json"
)
// ErrorType is an unsigned 64-bit error code as defined in the gin spec.
type ErrorType uint64
const (
// ErrorTypeBind is used when Context.Bind() fails.
Er... | type Error struct {
Err error
Type ErrorType
Meta any
}
type errorMsgs []*Error
var _ error = (*Error)(nil)
// SetType sets the error's type.
func (msg *Error) SetType(flags ErrorType) *Error {
msg.Type = flags
return msg
}
// SetMeta sets the er | ErrorType = 1 << 0
// ErrorTypePublic indicates a public error.
ErrorTypePublic ErrorType = 1 << 1
// ErrorTypeAny indicates any other error.
ErrorTypeAny ErrorType = 1<<64 - 1
)
// Error represents a error's specification.
| {
"filepath": "errors.go",
"language": "go",
"file_size": 3944,
"cut_index": 614,
"middle_length": 229
} |
InsecureSkipVerify: true,
},
}
client := &http.Client{Transport: tr}
resp, err := client.Get(params[0])
require.NoError(t, err)
defer resp.Body.Close()
body, ioerr := io.ReadAll(resp.Body)
require.NoError(t, ioerr)
responseStatus := "200 OK"
if len(params) > 1 && params[1] != "" {
responseStatus = param... | ntext) { c.String(http.StatusOK, "it worked") })
assert.NoError(t, router.Run())
}()
// Wait for server to be ready with exponential backoff
err := waitForServerReady("http://localhost:8080/example", 10)
require.NoError(t, err, "server should start | responseStatus == "200 OK" {
assert.Equal(t, responseBody, string(body), "resp body should match")
}
}
func TestRunEmpty(t *testing.T) {
os.Setenv("PORT", "")
router := New()
go func() {
router.GET("/example", func(c *Co | {
"filepath": "gin_integration_test.go",
"language": "go",
"file_size": 23533,
"cut_index": 1331,
"middle_length": 229
} |
/http"
"strings"
"testing"
"github.com/gin-contrib/sse"
"github.com/stretchr/testify/assert"
)
func TestMiddlewareGeneralCase(t *testing.T) {
signature := ""
router := New()
router.Use(func(c *Context) {
signature += "A"
c.Next()
signature += "B"
})
router.Use(func(c *Context) {
signature += "C"
})
... | (c *Context) {
signature += "A"
c.Next()
signature += "B"
})
router.Use(func(c *Context) {
signature += "C"
c.Next()
c.Next()
c.Next()
c.Next()
signature += "D"
})
router.NoRoute(func(c *Context) {
signature += "E"
c.Next()
sign | := PerformRequest(router, http.MethodGet, "/")
// TEST
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "ACDB", signature)
}
func TestMiddlewareNoRoute(t *testing.T) {
signature := ""
router := New()
router.Use(func | {
"filepath": "middleware_test.go",
"language": "go",
"file_size": 5371,
"cut_index": 716,
"middle_length": 229
} |
ord"
router.Use(RecoveryWithWriter(buffer))
router.GET("/recovery", func(c *Context) {
c.AbortWithStatus(http.StatusBadRequest)
panic("Oops, Houston, we have a problem")
})
// RUN
w := PerformRequest(router, http.MethodGet, "/recovery",
header{
Key: "Host",
Value: "www.google.com",
},
header{
... | ilder)
router := New()
router.Use(RecoveryWithWriter(buffer))
router.GET("/recovery", func(_ *Context) {
panic("Oops, Houston, we have a problem")
})
// RUN
w := PerformRequest(router, http.MethodGet, "/recovery")
// TEST
assert.Equal(t, http.Sta |
// Check the buffer does not have the secret key
assert.NotContains(t, buffer.String(), password)
}
// TestPanicInHandler assert that panic has been recovered.
func TestPanicInHandler(t *testing.T) {
buffer := new(strings.Bu | {
"filepath": "recovery_test.go",
"language": "go",
"file_size": 10918,
"cut_index": 921,
"middle_length": 229
} |
a boolean false .
func (ps Params) Get(name string) (string, bool) {
for _, entry := range ps {
if entry.Key == name {
return entry.Value, true
}
}
return "", false
}
// ByName returns the value of the first Param which key matches the given name.
// If no matching Param is found, an empty string is returne... | _ && a[i] == b[i] {
i++
}
return i
}
// addChild will add a child node, keeping wildcardChild at the end
func (n *node) addChild(child *node) {
if n.wildChild && len(n.children) > 0 {
wildcardChild := n.children[len(n.children)-1]
n.children = ap | dTrees) get(method string) *node {
for _, tree := range trees {
if tree.method == method {
return tree.root
}
}
return nil
}
func longestCommonPrefix(a, b string) int {
i := 0
max_ := min(len(a), len(b))
for i < max | {
"filepath": "tree.go",
"language": "go",
"file_size": 24381,
"cut_index": 1331,
"middle_length": 229
} |
yright 2017 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
//go:build !nomsgpack
package render
import (
"net/http"
"github.com/ugorji/go/codec"
)
// Check interface implemented here to support go build tag nomsg... | ack) encodes the given interface object and writes data with custom ContentType.
func (r MsgPack) Render(w http.ResponseWriter) error {
return WriteMsgPack(w, r.Data)
}
// WriteMsgPack writes MsgPack ContentType and encodes the given interface object.
fu | pe = []string{"application/msgpack; charset=utf-8"}
// WriteContentType (MsgPack) writes MsgPack ContentType.
func (r MsgPack) WriteContentType(w http.ResponseWriter) {
writeContentType(w, msgpackContentType)
}
// Render (MsgP | {
"filepath": "render/msgpack.go",
"language": "go",
"file_size": 1175,
"cut_index": 518,
"middle_length": 229
} |
// Copyright 2022 Gin Core Team. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package render
import (
"net/http"
"github.com/pelletier/go-toml/v2"
)
// TOML contains the given interface object.
type TOML struct {
Data any
}
var toml... | toml.Marshal(r.Data)
if err != nil {
return err
}
_, err = w.Write(bytes)
return err
}
// WriteContentType (TOML) writes TOML ContentType for response.
func (r TOML) WriteContentType(w http.ResponseWriter) {
writeContentType(w, tomlContentType)
}
| ter) error {
r.WriteContentType(w)
bytes, err := | {
"filepath": "render/toml.go",
"language": "go",
"file_size": 820,
"cut_index": 512,
"middle_length": 52
} |
2019 Gin Core Team. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package binding
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
var form = map[string][]string{
"name": {"mike"},
"friends": {"anna", "nicole... | esting.B) {
var s structFull
for b.Loop() {
err := mapForm(&s, form)
if err != nil {
b.Fatalf("Error on a form mapping")
}
}
b.StopTimer()
t := b
assert.Equal(t, "mike", s.Name)
assert.Equal(t, 25, s.Age)
assert.Equal(t, []string{"anna", | ends"`
ID *struct {
Number string `form:"id_number"`
DateOfIssue time.Time `form:"id_date" time_format:"2006-01-02" time_utc:"true"`
}
Nationality *string `form:"nationality"`
}
func BenchmarkMapFormFull(b *t | {
"filepath": "binding/form_mapping_benchmark_test.go",
"language": "go",
"file_size": 1468,
"cut_index": 524,
"middle_length": 229
} |
tobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = pro... | otoreflect.EnumDescriptor {
return file_test_proto_enumTypes[0].Descriptor()
}
func (FOO) Type() protoreflect.EnumType {
return &file_test_proto_enumTypes[0]
}
func (x FOO) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Dep | ring]int32{
"X": 17,
}
)
func (x FOO) Enum() *FOO {
p := new(FOO)
*p = x
return p
}
func (x FOO) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (FOO) Descriptor() pr | {
"filepath": "testdata/protoexample/test.pb.go",
"language": "go",
"file_size": 8374,
"cut_index": 716,
"middle_length": 229
} |
y a MIT style
// license that can be found in the LICENSE file.
package gin
import (
"encoding/base64"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestBasicAuth(t *testing.T) {
pairs := processAccounts(Accounts{
"admin": "password",
"foo": "bar",
"bar": "foo"... | c() {
processAccounts(Accounts{
"": "password",
"foo": "bar",
})
})
}
func TestBasicAuthSearchCredential(t *testing.T) {
pairs := processAccounts(Accounts{
"admin": "password",
"foo": "bar",
"bar": "foo",
})
user, found := pair | vOmJhcg==",
})
assert.Contains(t, pairs, authPair{
user: "admin",
value: "Basic YWRtaW46cGFzc3dvcmQ=",
})
}
func TestBasicAuthFails(t *testing.T) {
assert.Panics(t, func() { processAccounts(nil) })
assert.Panics(t, fun | {
"filepath": "auth_test.go",
"language": "go",
"file_size": 5074,
"cut_index": 614,
"middle_length": 229
} |
writermem responseWriter
Request *http.Request
Writer ResponseWriter
Params Params
handlers HandlersChain
index int8
fullPath string
engine *Engine
params *Params
skippedNodes *[]skippedNode
// This mutex protects Keys map.
mu sync.RWMutex
// Keys is a key/value pair exclusively fo... | ed form data from POST, PATCH,
// or PUT body parameters.
formCache url.Values
// SameSite allows a server to define a cookie attribute making it impossible for
// the browser to send this cookie along with cross-site requests.
sameSite http.SameSite | of manually accepted formats for content negotiation.
Accepted []string
// queryCache caches the query result from c.Request.URL.Query().
queryCache url.Values
// formCache caches c.Request.PostForm, which contains the pars | {
"filepath": "context.go",
"language": "go",
"file_size": 46437,
"cut_index": 2151,
"middle_length": 229
} |
fy/assert"
)
// TestContextFileSimple tests the Context.File() method with a simple case
func TestContextFileSimple(t *testing.T) {
// Test serving an existing file
testFile := "testdata/test_file.txt"
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/test"... | ving a non-existent file
func TestContextFileNotFound(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)
c.File("non_existent_file.txt")
assert.Equal(t, http.StatusN | tent-Type"))
}
// TestContextFileNotFound tests ser | {
"filepath": "context_file_test.go",
"language": "go",
"file_size": 933,
"cut_index": 606,
"middle_length": 52
} |
reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package gin
import (
"fmt"
"html/template"
"runtime"
"strconv"
"strings"
"sync/atomic"
)
const ginSupportMinGoVer = 25
var runtimeVersion = runtime.Version()
// IsDebugging returns true if the f... | y)
func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) {
if IsDebugging() {
nuHandlers := len(handlers)
handlerName := nameOfFunction(handlers.Last())
if DebugPrintRouteFunc == nil {
debugPrint("%-6s %-25s --> %s (%d ha | dicates debug log output format.
var DebugPrintRouteFunc func(httpMethod, absolutePath, handlerName string, nuHandlers int)
// DebugPrintFunc indicates debug log output format.
var DebugPrintFunc func(format string, values ...an | {
"filepath": "debug.go",
"language": "go",
"file_size": 3000,
"cut_index": 563,
"middle_length": 229
} |
"
"html/template"
"io"
"log"
"net/http"
"os"
"strings"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestIsDebugging(t *testing.T) {
SetMode(DebugMode)
assert.True(t, IsDebugging())
SetMode(ReleaseMode)
assert.False(t, IsDebugging())
SetMode(TestMode... | sting.T) {
DebugPrintFunc = func(format string, values ...any) {
fmt.Fprintf(DefaultWriter, "[GIN-debug] "+format, values...)
}
re := captureOutput(t, func() {
SetMode(DebugMode)
debugPrint("debug print func test: %d", 123)
SetMode(TestMode)
}) | Mode)
debugPrint("DEBUG this!")
SetMode(DebugMode)
debugPrint("these are %d %s", 2, "error messages")
SetMode(TestMode)
})
assert.Equal(t, "[GIN-debug] these are 2 error messages\n", re)
}
func TestDebugPrintFunc(t *te | {
"filepath": "debug_test.go",
"language": "go",
"file_size": 5413,
"cut_index": 716,
"middle_length": 229
} |
y a MIT style
// license that can be found in the LICENSE file.
package gin
import (
"errors"
"fmt"
"testing"
"github.com/gin-gonic/gin/codec/json"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestError(t *testing.T) {
baseError := errors.New("test error")
err := &Error{... | err.JSON())
jsonBytes, _ := json.API.Marshal(err)
assert.JSONEq(t, "{\"error\":\"test error\",\"meta\":\"some data\"}", string(jsonBytes))
err.SetMeta(H{ //nolint: errcheck
"status": "200",
"data": "some data",
})
assert.Equal(t, H{
"error" | rTypePublic), err)
assert.Equal(t, ErrorTypePublic, err.Type)
assert.Equal(t, err.SetMeta("some data"), err)
assert.Equal(t, "some data", err.Meta)
assert.Equal(t, H{
"error": baseError.Error(),
"meta": "some data",
}, | {
"filepath": "errors_test.go",
"language": "go",
"file_size": 4297,
"cut_index": 614,
"middle_length": 229
} |
import (
"errors"
"net/http"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type mockFileSystem struct {
open func(name string) (http.File, error)
}
func (m *mockFileSystem) Open(name string) (http.File, error) {
return m.open(name)
}
func TestOnlyFilesFS_Open(t... | func(_ string) (http.File, error) {
return nil, testError
},
}
fs := &OnlyFilesFS{FileSystem: mockFS}
file, err := fs.Open("foo")
require.ErrorIs(t, err, testError)
assert.Nil(t, file)
}
func Test_neuteredReaddirFile_Readdir(t *testing.T) {
| err := fs.Open("foo")
require.NoError(t, err)
assert.Equal(t, testFile, file.(neutralizedReaddirFile).File)
}
func TestOnlyFilesFS_Open_err(t *testing.T) {
testError := errors.New("mock")
mockFS := &mockFileSystem{
open: | {
"filepath": "fs_test.go",
"language": "go",
"file_size": 1395,
"cut_index": 524,
"middle_length": 229
} |
2017 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package gin
import (
"net/http"
"os"
)
// OnlyFilesFS implements an http.FileSystem without `Readdir` functionality.
type OnlyFilesFS struct {
FileSystem http.F... | ir overrides the http.File default implementation and always returns nil.
func (n neutralizedReaddirFile) Readdir(_ int) ([]os.FileInfo, error) {
// this disables directory listing
return nil, nil
}
// Dir returns an http.FileSystem that can be used by | )
if err != nil {
return nil, err
}
return neutralizedReaddirFile{f}, nil
}
// neutralizedReaddirFile wraps http.File with a specific implementation of `Readdir`.
type neutralizedReaddirFile struct {
http.File
}
// Readd | {
"filepath": "fs.go",
"language": "go",
"file_size": 1396,
"cut_index": 524,
"middle_length": 229
} |
// 0.0.0.0/0 (IPv4)
IP: net.IP{0x0, 0x0, 0x0, 0x0},
Mask: net.IPMask{0x0, 0x0, 0x0, 0x0},
},
{ // ::/0 (IPv6)
IP: net.IP{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
Mask: net.IPMask{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
},
}... |
if length := len(c); length > 0 {
return c[length-1]
}
return nil
}
// RouteInfo represents a request route's specification which contains method and path and its handler.
type RouteInfo struct {
Method string
Path string
Handler | Func func(*Engine)
// HandlersChain defines a HandlerFunc slice.
type HandlersChain []HandlerFunc
// Last returns the last handler in the chain. i.e. the last handler is the main one.
func (c HandlersChain) Last() HandlerFunc { | {
"filepath": "gin.go",
"language": "go",
"file_size": 27227,
"cut_index": 1331,
"middle_length": 229
} |
/:access_token"},
{http.MethodDelete, "/applications/:client_id/tokens"},
{http.MethodDelete, "/applications/:client_id/tokens/:access_token"},
// Activity
{http.MethodGet, "/events"},
{http.MethodGet, "/repos/:owner/:repo/events"},
{http.MethodGet, "/networks/:owner/:repo/events"},
{http.MethodGet, "/orgs/:org... |
{http.MethodPut, "/repos/:owner/:repo/notifications"},
{http.MethodGet, "/notifications/threads/:id"},
//{http.MethodPatch, "/notifications/threads/:id"},
{http.MethodGet, "/notifications/threads/:id/subscription"},
{http.MethodPut, "/notifications/t | r/events/public"},
{http.MethodGet, "/users/:user/events/orgs/:org"},
{http.MethodGet, "/feeds"},
{http.MethodGet, "/notifications"},
{http.MethodGet, "/repos/:owner/:repo/notifications"},
{http.MethodPut, "/notifications"}, | {
"filepath": "githubapi_test.go",
"language": "go",
"file_size": 17383,
"cut_index": 1331,
"middle_length": 229
} |
outer.Use(LoggerWithWriter(buffer))
router.GET("/example", func(c *Context) {})
router.POST("/example", func(c *Context) {})
router.PUT("/example", func(c *Context) {})
router.DELETE("/example", func(c *Context) {})
router.PATCH("/example", func(c *Context) {})
router.HEAD("/example", func(c *Context) {})
router... | whole logging process rather
// than individual functions. I'm not sure where these should go.
buffer.Reset()
PerformRequest(router, http.MethodPost, "/example")
assert.Contains(t, buffer.String(), "200")
assert.Contains(t, buffer.String(), http.Metho | dGet)
assert.Contains(t, buffer.String(), "/example")
assert.Contains(t, buffer.String(), "a=100")
// I wrote these first (extending the above) but then realized they are more
// like integration tests because they test the | {
"filepath": "logger_test.go",
"language": "go",
"file_size": 15933,
"cut_index": 921,
"middle_length": 229
} |
net/http"
"os"
"time"
"github.com/mattn/go-isatty"
)
type consoleColorModeValue int
const (
autoColor consoleColorModeValue = iota
disableColor
forceColor
)
const (
green = "\033[97;42m"
white = "\033[90;47m"
yellow = "\033[90;43m"
red = "\033[97;41m"
blue = "\033[97;44m"
magenta = "\033[97;... | written.
// Optional.
SkipPaths []string
// SkipQueryString indicates that query strings should not be written
// for cases such as when API keys are passed via query strings.
// Optional. Default value is false.
SkipQueryString bool
// Skip is a | lt value is gin.defaultLogFormatter
Formatter LogFormatter
// Output is a writer where logs are written.
// Optional. Default value is gin.DefaultWriter.
Output io.Writer
// SkipPaths is a URL path array which logs are not | {
"filepath": "logger.go",
"language": "go",
"file_size": 8070,
"cut_index": 716,
"middle_length": 229
} |
.SetFuncMap(template.FuncMap{
"formatAsDate": formatAsDate,
})
loadMethod(router)
router.GET("/test", func(c *Context) {
c.HTML(http.StatusOK, "hello.tmpl", map[string]string{"name": "world"})
})
router.GET("/raw", func(c *Context) {
c.HTML(http.StatusOK, "raw.tmpl", map[string]any{
"now": time.D... | tp.Get(ts.URL + "/test")
if err != nil {
t.Error(err)
}
resp, _ := io.ReadAll(res.Body)
assert.Equal(t, "<h1>Hello world</h1>", string(resp))
}
func TestH2c(t *testing.T) {
ln, err := net.Listen("tcp", localhostIP+":0")
if err != nil {
t.Error( | }
return ts
}
func TestLoadHTMLGlobDebugMode(t *testing.T) {
ts := setupHTMLFiles(
t,
DebugMode,
false,
func(router *Engine) {
router.LoadHTMLGlob("./testdata/template/*")
},
)
defer ts.Close()
res, err := ht | {
"filepath": "gin_test.go",
"language": "go",
"file_size": 28333,
"cut_index": 1331,
"middle_length": 229
} |
rtinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package gin
import (
"os"
"sync/atomic"
"testing"
"github.com/gin-gonic/gin/binding"
"github.com/stretchr/testify/assert"
)
func init() {
os.Setenv(EnvGinMode, TestMode)... | Equal(t, int32(releaseCode), atomic.LoadInt32(&ginMode))
assert.Equal(t, ReleaseMode, Mode())
SetMode(TestMode)
assert.Equal(t, int32(testCode), atomic.LoadInt32(&ginMode))
assert.Equal(t, TestMode, Mode())
assert.Panics(t, func() { SetMode("unknown | t32(testCode), atomic.LoadInt32(&ginMode))
assert.Equal(t, TestMode, Mode())
SetMode(DebugMode)
assert.Equal(t, int32(debugCode), atomic.LoadInt32(&ginMode))
assert.Equal(t, DebugMode, Mode())
SetMode(ReleaseMode)
assert. | {
"filepath": "mode_test.go",
"language": "go",
"file_size": 1635,
"cut_index": 537,
"middle_length": 229
} |
e Go Authors.
// Use of this source code is governed by a BSD-style license that can be found
// at https://github.com/julienschmidt/httprouter/blob/master/LICENSE.
package gin
const stackBufSize = 128
// cleanPath is the URL version of path.Clean, it returns a canonical URL path
// for p, eliminating . and .. eleme... | ace "/.." by "/" at the beginning of a path.
//
// If the result of this process is an empty string, "/" is returned.
func cleanPath(p string) string {
// Turn empty string into "/"
if p == "" {
return "/"
}
// Reasonably sized buffer on stack to av | t (the current directory).
// 3. Eliminate each inner .. path name element (the parent directory)
// along with the non-.. element that precedes it.
// 4. Eliminate .. elements that begin a rooted path:
// that is, repl | {
"filepath": "path.go",
"language": "go",
"file_size": 4911,
"cut_index": 614,
"middle_length": 229
} |
reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package gin
import (
"flag"
"io"
"os"
"sync/atomic"
"github.com/gin-gonic/gin/binding"
)
// EnvGinMode indicates environment name for gin mode.
const EnvGinMode = "GIN_MODE"
const (
// DebugMode... | to configure their
// output io.Writer.
// To support coloring in Windows use:
//
// import "github.com/mattn/go-colorable"
// gin.DefaultWriter = colorable.NewColorableStdout()
var DefaultWriter io.Writer = os.Stdout
// DefaultErrorWriter is the default | (
debugCode = iota
releaseCode
testCode
)
// DefaultWriter is the default io.Writer used by Gin for debug output and
// middleware output like Logger() or Recovery().
// Note that both Logger and Recovery provides custom ways | {
"filepath": "mode.go",
"language": "go",
"file_size": 2456,
"cut_index": 563,
"middle_length": 229
} |
s"
"cmp"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/http/httputil"
"os"
"runtime"
"strings"
"syscall"
"time"
"github.com/gin-gonic/gin/internal/bytesconv"
)
const (
dunno = "???"
stackSkip = 3
)
// RecoveryFunc defines the function passable to CustomRecovery.
type RecoveryFunc func(c *Context, err ... | overyWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one.
func RecoveryWithWriter(out io.Writer, recovery ...RecoveryFunc) HandlerFunc {
if len(recovery) > 0 {
return CustomRecoveryWithWrite | mRecovery returns a middleware that recovers from any panics and calls the provided handle func to handle it.
func CustomRecovery(handle RecoveryFunc) HandlerFunc {
return RecoveryWithWriter(DefaultErrorWriter, handle)
}
// Rec | {
"filepath": "recovery.go",
"language": "go",
"file_size": 5720,
"cut_index": 716,
"middle_length": 229
} |
e Go Authors.
// Use of this source code is governed by a BSD-style license that can be found
// at https://github.com/julienschmidt/httprouter/blob/master/LICENSE
package gin
import (
"runtime"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
type cleanPathTest struct {
path, result string
}
var cl... | c", "/abc"},
{"///abc", "/abc"},
{"//abc//", "/abc/"},
// Remove . elements
{".", "/"},
{"./", "/"},
{"/abc/./def", "/abc/def"},
{"/./abc/def", "/abc/def"},
{"/abc/.", "/abc/"},
// Remove .. elements
{"..", "/"},
{"../", "/"},
{"../../", "/"} |
{"abc", "/abc"},
{"abc/def", "/abc/def"},
{"a/b/c", "/a/b/c"},
// Remove doubled slash
{"//", "/"},
{"/abc//", "/abc/"},
{"/abc/def//", "/abc/def/"},
{"/a/b/c//", "/a/b/c/"},
{"/abc//def//ghi", "/abc/def/ghi"},
{"//ab | {
"filepath": "path_test.go",
"language": "go",
"file_size": 3726,
"cut_index": 614,
"middle_length": 229
} |
y a MIT style
// license that can be found in the LICENSE file.
package gin
import (
"bufio"
"errors"
"io"
"net"
"net/http"
)
const (
noWritten = -1
defaultStatus = http.StatusOK
)
var errHijackAlreadyWritten = errors.New("gin: response body already written")
// ResponseWriter ...
type ResponseWriter in... | was already written.
Written() bool
// WriteHeaderNow forces to write the http header (status code + headers).
WriteHeaderNow()
// Pusher get the http.Pusher for server push
Pusher() http.Pusher
}
type responseWriter struct {
http.ResponseWriter
| mber of bytes already written into the response http body.
// See Written()
Size() int
// WriteString writes the string into the response body.
WriteString(string) (int, error)
// Written returns true if the response body | {
"filepath": "response_writer.go",
"language": "go",
"file_size": 3263,
"cut_index": 614,
"middle_length": 229
} |
ng{
http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch,
http.MethodHead, http.MethodOptions, http.MethodDelete, http.MethodConnect,
http.MethodTrace,
}
)
// IRouter defines all router handle interface includes single and group router.
type IRouter interface {
IRoutes
Group(string, ...HandlerFun... | dlerFunc) IRoutes
HEAD(string, ...HandlerFunc) IRoutes
Match([]string, string, ...HandlerFunc) IRoutes
StaticFile(string, string) IRoutes
StaticFileFS(string, string, http.FileSystem) IRoutes
Static(string, string) IRoutes
StaticFS(string, http.File | rFunc) IRoutes
GET(string, ...HandlerFunc) IRoutes
POST(string, ...HandlerFunc) IRoutes
DELETE(string, ...HandlerFunc) IRoutes
PATCH(string, ...HandlerFunc) IRoutes
PUT(string, ...HandlerFunc) IRoutes
OPTIONS(string, ...Han | {
"filepath": "routergroup.go",
"language": "go",
"file_size": 9279,
"cut_index": 921,
"middle_length": 229
} |
esting"
"github.com/stretchr/testify/assert"
)
var MaxHandlers = 32
func init() {
SetMode(TestMode)
}
func TestRouterGroupBasic(t *testing.T) {
router := New()
group := router.Group("/hola", func(c *Context) {})
group.Use(func(c *Context) {})
assert.Len(t, group.Handlers, 2)
assert.Equal(t, "/hola", group.B... | t, http.MethodPut)
performRequestInGroup(t, http.MethodPatch)
performRequestInGroup(t, http.MethodDelete)
performRequestInGroup(t, http.MethodHead)
performRequestInGroup(t, http.MethodOptions)
}
func performRequestInGroup(t *testing.T, method string) | ola/manu", group2.BasePath())
assert.Equal(t, router, group2.engine)
}
func TestRouterGroupBasicHandle(t *testing.T) {
performRequestInGroup(t, http.MethodGet)
performRequestInGroup(t, http.MethodPost)
performRequestInGroup( | {
"filepath": "routergroup_test.go",
"language": "go",
"file_size": 5970,
"cut_index": 716,
"middle_length": 229
} |
ny("/test2", func(c *Context) {
passedAny = true
})
r.Handle(method, "/test", func(c *Context) {
passed = true
})
w := PerformRequest(r, method, "/test")
assert.True(t, passed)
assert.Equal(t, http.StatusOK, w.Code)
PerformRequest(r, method, "/test2")
assert.True(t, passedAny)
}
// TestSingleRouteOK test... | t *testing.T) {
passed := false
router := New()
router.HandleMethodNotAllowed = true
var methodRoute string
if method == http.MethodPost {
methodRoute = http.MethodGet
} else {
methodRoute = http.MethodPost
}
router.Handle(methodRoute, "/test", | e
})
w := PerformRequest(router, method, "/test")
assert.False(t, passed)
assert.Equal(t, http.StatusNotFound, w.Code)
}
// TestSingleRouteOK tests that POST route is correctly invoked.
func testRouteNotOK2(method string, | {
"filepath": "routes_test.go",
"language": "go",
"file_size": 24774,
"cut_index": 1331,
"middle_length": 229
} |
rtinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package gin
import (
"fmt"
"net/http"
"time"
)
// CreateTestContext returns a fresh Engine and a Context associated with it.
// This is useful for tests that need to set up ... | ed Engine `r`.
// This is useful for tests that operate on an existing, possibly pre-configured,
// Gin engine instance and need a new context for it.
// The ResponseWriter `w` is used to initialize the context's writer.
// The context is allocated with th |
func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) {
r = New()
c = r.allocateContext(0)
c.reset()
c.writermem.reset(w)
return
}
// CreateTestContextOnly returns a fresh Context associated with the provid | {
"filepath": "test_helpers.go",
"language": "go",
"file_size": 1902,
"cut_index": 537,
"middle_length": 229
} |
r) {
// func (w *responseWriter) CloseNotify() <-chan bool {
// func (w *responseWriter) Flush() {
var (
_ ResponseWriter = &responseWriter{}
_ http.ResponseWriter = &responseWriter{}
_ http.ResponseWriter = ResponseWriter(&responseWriter{})
_ http.Hijacker = ResponseWriter(&responseWriter{})
_ http.Fl... | ter := &responseWriter{}
var w ResponseWriter = writer
writer.reset(testWriter)
assert.Equal(t, -1, writer.size)
assert.Equal(t, http.StatusOK, writer.status)
assert.Equal(t, testWriter, writer.ResponseWriter)
assert.Equal(t, -1, w.Size())
assert.E |
testWriter := httptest.NewRecorder()
writer := &responseWriter{ResponseWriter: testWriter}
assert.Same(t, testWriter, writer.Unwrap())
}
func TestResponseWriterReset(t *testing.T) {
testWriter := httptest.NewRecorder()
wri | {
"filepath": "response_writer_test.go",
"language": "go",
"file_size": 9282,
"cut_index": 921,
"middle_length": 229
} |
e '%s'", request.path)
}
}
}
}
func checkPriorities(t *testing.T, n *node) uint32 {
var prio uint32
for i := range n.children {
prio += checkPriorities(t, n.children[i])
}
if n.handlers != nil {
prio++
}
if n.priority != prio {
t.Errorf(
"priority mismatch for node '%s': is %d, should be %d",
... | l",
"/α",
"/β",
}
for _, route := range routes {
tree.addRoute(route, fakeHandler(route))
}
checkRequests(t, tree, testRequests{
{"/a", false, "/a", nil},
{"/", true, "", nil},
{"/hi", false, "/hi", nil},
{"/contact", false, "/contact", | "/:param", 256)) != 256 {
t.Fail()
}
}
func TestTreeAddAndGet(t *testing.T) {
tree := &node{}
routes := [...]string{
"/hi",
"/contact",
"/co",
"/c",
"/a",
"/ab",
"/doc/",
"/doc/go_faq.html",
"/doc/go1.htm | {
"filepath": "tree_test.go",
"language": "go",
"file_size": 35988,
"cut_index": 2151,
"middle_length": 229
} |
e"
"net/http"
"sync"
"github.com/gin-gonic/gin"
)
var engine = sync.OnceValue(func() *gin.Engine {
return gin.Default()
})
// LoadHTMLGlob is a wrapper for Engine.LoadHTMLGlob.
func LoadHTMLGlob(pattern string) {
engine().LoadHTMLGlob(pattern)
}
// LoadHTMLFiles is a wrapper for Engine.LoadHTMLFiles.
func Load... | y default.
func NoRoute(handlers ...gin.HandlerFunc) {
engine().NoRoute(handlers...)
}
// NoMethod is a wrapper for Engine.NoMethod.
func NoMethod(handlers ...gin.HandlerFunc) {
engine().NoMethod(handlers...)
}
// Group creates a new router group. You | FS(fs, patterns...)
}
// SetHTMLTemplate is a wrapper for Engine.SetHTMLTemplate.
func SetHTMLTemplate(templ *template.Template) {
engine().SetHTMLTemplate(templ)
}
// NoRoute adds handlers for NoRoute. It returns a 404 code b | {
"filepath": "ginS/gins.go",
"language": "go",
"file_size": 5654,
"cut_index": 716,
"middle_length": 229
} |
Copyright 2025 Gin Core Team. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package render
import (
"net/http"
"go.mongodb.org/mongo-driver/v2/bson"
)
// BSON contains the given interface object.
type BSON struct {
Data any
}
var bs... | tType(w)
bytes, err := bson.Marshal(&r.Data)
if err == nil {
_, err = w.Write(bytes)
}
return err
}
// WriteContentType (BSONBuf) writes BSONBuf ContentType.
func (r BSON) WriteContentType(w http.ResponseWriter) {
writeContentType(w, bsonContentTy | r.WriteConten | {
"filepath": "render/bson.go",
"language": "go",
"file_size": 790,
"cut_index": 514,
"middle_length": 14
} |
y a MIT style
// license that can be found in the LICENSE file.
package render
import (
"bytes"
"fmt"
"html/template"
"net/http"
"unicode"
"github.com/gin-gonic/gin/codec/json"
"github.com/gin-gonic/gin/internal/bytesconv"
)
// JSON contains the given interface object.
type JSON struct {
Data any
}
// Inde... | eJSON contains the given interface object.
type PureJSON struct {
Data any
}
var (
jsonContentType = []string{"application/json; charset=utf-8"}
jsonpContentType = []string{"application/javascript; charset=utf-8"}
jsonASCIIContentType = []str | Data any
}
// JsonpJSON contains the given interface object its callback.
type JsonpJSON struct {
Callback string
Data any
}
// AsciiJSON contains the given interface object.
type AsciiJSON struct {
Data any
}
// Pur | {
"filepath": "render/json.go",
"language": "go",
"file_size": 5013,
"cut_index": 614,
"middle_length": 229
} |
y a MIT style
// license that can be found in the LICENSE file.
package gin
import (
"bytes"
"encoding/xml"
"fmt"
"math"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func init() {
SetMode(TestMode)
}
func BenchmarkParseAccept(b *testing.B) {
for b.Loop... | w()
router.POST("/path", WrapH(&testStruct{t}))
router.GET("/path2", WrapF(func(w http.ResponseWriter, req *http.Request) {
assert.Equal(t, http.MethodGet, req.Method)
assert.Equal(t, "/path2", req.URL.Path)
w.WriteHeader(http.StatusBadRequest)
f | req *http.Request) {
assert.Equal(t.T, http.MethodPost, req.Method)
assert.Equal(t.T, "/path", req.URL.Path)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "hello")
}
func TestWrap(t *testing.T) {
router := Ne | {
"filepath": "utils_test.go",
"language": "go",
"file_size": 4604,
"cut_index": 614,
"middle_length": 229
} |
/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func init() {
gin.SetMode(gin.TestMode)
}
func TestGET(t *testing.T) {
GET("/test", func(c *gin.Context) {
c.String(http.StatusOK, "test")
})
req := httptest.NewRequest(http.MethodGet, "/test", nil)
w :... | rt.Equal(t, "created", w.Body.String())
}
func TestPUT(t *testing.T) {
PUT("/put", func(c *gin.Context) {
c.String(http.StatusOK, "updated")
})
req := httptest.NewRequest(http.MethodPut, "/put", nil)
w := httptest.NewRecorder()
engine().ServeHTTP( | gin.Context) {
c.String(http.StatusCreated, "created")
})
req := httptest.NewRequest(http.MethodPost, "/post", nil)
w := httptest.NewRecorder()
engine().ServeHTTP(w, req)
assert.Equal(t, http.StatusCreated, w.Code)
asse | {
"filepath": "ginS/gins_test.go",
"language": "go",
"file_size": 5862,
"cut_index": 716,
"middle_length": 229
} |
reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package render
import (
"html/template"
"net/http"
"github.com/gin-gonic/gin/internal/fs"
)
// Delims represents a set of Left and Right delimiters for HTML template rendering.
type Delims struct {
... | // HTMLDebug contains template delims and pattern and function with file list.
type HTMLDebug struct {
Files []string
Glob string
FileSystem http.FileSystem
Patterns []string
Delims Delims
FuncMap template.FuncMap
}
// HTML conta | nder interface {
// Instance returns an HTML instance.
Instance(string, any) Render
}
// HTMLProduction contains template reference and its delims.
type HTMLProduction struct {
Template *template.Template
Delims Delims
}
| {
"filepath": "render/html.go",
"language": "go",
"file_size": 2875,
"cut_index": 563,
"middle_length": 229
} |
y a MIT style
// license that can be found in the LICENSE file.
package gin
import (
"encoding/xml"
"math"
"net/http"
"os"
"path"
"reflect"
"runtime"
"strings"
"unicode"
)
// BindKey indicates a default bind key.
const BindKey = "_gin-gonic/gin/bindkey"
// localhostIP indicates the default localhost IP add... | )
`)
}
typ := value.Type()
return func(c *Context) {
obj := reflect.New(typ).Interface()
if c.Bind(obj) == nil {
c.Set(BindKey, obj)
}
}
}
// WrapF is a helper function for wrapping http.HandlerFunc and returns a Gin middleware.
func WrapF(f | eturns a Gin middleware.
func Bind(val any) HandlerFunc {
value := reflect.ValueOf(val)
if value.Kind() == reflect.Ptr {
panic(`Bind struct can not be a pointer. Example:
Use: gin.Bind(Struct{}) instead of gin.Bind(&Struct{} | {
"filepath": "utils.go",
"language": "go",
"file_size": 4117,
"cut_index": 614,
"middle_length": 229
} |
yright 2018 Gin Core Team. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package render
import (
"io"
"net/http"
"strconv"
)
// Reader contains the IO reader and its length, and custom ContentType and other headers.
type Reader struct ... | r.writeHeaders(w)
_, err = io.Copy(w, r.Reader)
return
}
// WriteContentType (Reader) writes custom ContentType.
func (r Reader) WriteContentType(w http.ResponseWriter) {
writeContentType(w, []string{r.ContentType})
}
// writeHeaders writes headers f | nder(w http.ResponseWriter) (err error) {
r.WriteContentType(w)
if r.ContentLength >= 0 {
if r.Headers == nil {
r.Headers = map[string]string{}
}
r.Headers["Content-Length"] = strconv.FormatInt(r.ContentLength, 10)
}
| {
"filepath": "render/reader.go",
"language": "go",
"file_size": 1195,
"cut_index": 518,
"middle_length": 229
} |
eida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package render
import (
"fmt"
"net/http"
)
// Redirect contains the http request reference and redirects status code and location.
type Redirect struct {
Code int
Request *http.... | rmanentRedirect) && r.Code != http.StatusCreated {
panic(fmt.Sprintf("Cannot redirect with status code %d", r.Code))
}
http.Redirect(w, r.Request, r.Location, r.Code)
return nil
}
// WriteContentType (Redirect) don't write any ContentType.
func (r Re | http.StatusMultipleChoices || r.Code > http.StatusPe | {
"filepath": "render/redirect.go",
"language": "go",
"file_size": 904,
"cut_index": 547,
"middle_length": 52
} |
Error(t, err)
assert.JSONEq(t, "{\"foo\":\"bar\",\"html\":\"\\u003cb\\u003e\"}", w.Body.String())
assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
}
func TestRenderJSONError(t *testing.T) {
w := httptest.NewRecorder()
data := make(chan int)
// json: unsupported type: chan int
r... | TestRenderIndentedJSONPanics(t *testing.T) {
w := httptest.NewRecorder()
data := make(chan int)
// json: unsupported type: chan int
err := (IndentedJSON{data}).Render(w)
require.Error(t, err)
}
func TestRenderSecureJSON(t *testing.T) {
w1 := httpt | edJSON{data}).Render(w)
require.NoError(t, err)
assert.JSONEq(t, "{\n \"bar\": \"foo\",\n \"foo\": \"bar\"\n}", w.Body.String())
assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
}
func | {
"filepath": "render/render_test.go",
"language": "go",
"file_size": 20859,
"cut_index": 1331,
"middle_length": 229
} |
Copyright 2014 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package render
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin/internal/bytesconv"
)
// String contains the given interface object slice and its f... | tType)
}
// WriteString writes data according to its format and write custom ContentType.
func WriteString(w http.ResponseWriter, format string, data []any) (err error) {
writeContentType(w, plainContentType)
if len(data) > 0 {
_, err = fmt.Fprintf(w, | ) Render(w http.ResponseWriter) error {
return WriteString(w, r.Format, r.Data)
}
// WriteContentType (String) writes Plain ContentType.
func (r String) WriteContentType(w http.ResponseWriter) {
writeContentType(w, plainConten | {
"filepath": "render/text.go",
"language": "go",
"file_size": 1091,
"cut_index": 515,
"middle_length": 229
} |
yright 2014 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package render
import "net/http"
// Render interface is to be implemented by JSON, XML, HTML, YAML and so on.
type Render interface {
// Render writes data ... | er = (*HTML)(nil)
_ HTMLRender = (*HTMLDebug)(nil)
_ HTMLRender = (*HTMLProduction)(nil)
_ Render = (*YAML)(nil)
_ Render = (*Reader)(nil)
_ Render = (*AsciiJSON)(nil)
_ Render = (*ProtoBuf)(nil)
_ Render = (*TOML)(nil)
_ Re | nder = (*IndentedJSON)(nil)
_ Render = (*SecureJSON)(nil)
_ Render = (*JsonpJSON)(nil)
_ Render = (*XML)(nil)
_ Render = (*String)(nil)
_ Render = (*Redirect)(nil)
_ Render = (*Data)(nil)
_ Rend | {
"filepath": "render/render.go",
"language": "go",
"file_size": 1203,
"cut_index": 518,
"middle_length": 229
} |
Gin Core Team. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package render
import (
"net/http"
"google.golang.org/protobuf/proto"
)
// ProtoBuf contains the given interface object.
type ProtoBuf struct {
Data any
}
var protobufCont... | .Marshal(r.Data.(proto.Message))
if err != nil {
return err
}
_, err = w.Write(bytes)
return err
}
// WriteContentType (ProtoBuf) writes ProtoBuf ContentType.
func (r ProtoBuf) WriteContentType(w http.ResponseWriter) {
writeContentType(w, protobuf | error {
r.WriteContentType(w)
bytes, err := proto | {
"filepath": "render/protobuf.go",
"language": "go",
"file_size": 852,
"cut_index": 529,
"middle_length": 52
} |
rtinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
//go:build !nomsgpack
package render
import (
"errors"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.c... | derBytes(w.Body.Bytes(), &mh).Decode(&decoded)
require.NoError(t, err)
assert.Equal(t, data, decoded)
assert.Equal(t, "application/msgpack; charset=utf-8", w.Header().Get("Content-Type"))
}
func TestWriteMsgPack(t *testing.T) {
w := httptest.NewRecord | pplication/msgpack; charset=utf-8", w.Header().Get("Content-Type"))
err := (MsgPack{data}).Render(w)
require.NoError(t, err)
var decoded map[string]any
var mh codec.MsgpackHandle
mh.RawToString = true
err = codec.NewDeco | {
"filepath": "render/render_msgpack_test.go",
"language": "go",
"file_size": 1902,
"cut_index": 537,
"middle_length": 229
} |
/ Copyright 2014 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package render
import (
"net/http"
"github.com/goccy/go-yaml"
)
// YAML contains the given interface object.
type YAML struct {
Data any
}
var yaml... | yaml.Marshal(r.Data)
if err != nil {
return err
}
_, err = w.Write(bytes)
return err
}
// WriteContentType (YAML) writes YAML ContentType for response.
func (r YAML) WriteContentType(w http.ResponseWriter) {
writeContentType(w, yamlContentType)
}
| ter) error {
r.WriteContentType(w)
bytes, err := | {
"filepath": "render/yaml.go",
"language": "go",
"file_size": 821,
"cut_index": 513,
"middle_length": 52
} |
y a MIT style
// license that can be found in the LICENSE file.
//go:build !nomsgpack
package binding
import "net/http"
// Content-Type MIME of the most common data formats.
const (
MIMEJSON = "application/json"
MIMEHTML = "text/html"
MIMEXML = "application/xml"
MIMEXML2 ... | = "application/toml"
MIMEBSON = "application/bson"
)
// Binding describes the interface which needs to be implemented for binding the
// data present in the request such as JSON request body, query parameters or
// the form POST.
t | = "application/x-protobuf"
MIMEMSGPACK = "application/x-msgpack"
MIMEMSGPACK2 = "application/msgpack"
MIMEYAML = "application/x-yaml"
MIMEYAML2 = "application/yaml"
MIMETOML | {
"filepath": "binding/binding.go",
"language": "go",
"file_size": 4294,
"cut_index": 614,
"middle_length": 229
} |
2020 Gin Core Team. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
//go:build !nomsgpack
package binding
import (
"bytes"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/u... | ding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
assert.Equal(t, name, b.Name())
obj := FooStruct{}
req := requestWithBody(http.MethodPost, path, body)
req.Header.Add("Content-Type", MIMEMSGPACK)
err := b.Bind(req, &obj)
re | otNil(t, buf)
err := codec.NewEncoder(buf, h).Encode(test)
require.NoError(t, err)
data := buf.Bytes()
testMsgPackBodyBinding(t,
MsgPack, "msgpack",
"/", "/",
string(data), string(data[1:]))
}
func testMsgPackBodyBin | {
"filepath": "binding/binding_msgpack_test.go",
"language": "go",
"file_size": 1423,
"cut_index": 524,
"middle_length": 229
} |
time.Time `form:"time_bar" time_format:"2006-01-02" time_utc:"1"`
CreateTime time.Time `form:"createTime" time_format:"unixNano"`
UnixTime time.Time `form:"unixTime" time_format:"unix"`
UnixMilliTime time.Time `form:"unixMilliTime" time_format:"unixmilli"`
UnixMicroTime time.Time `form:"unixMicroTime" time... | me_foo"`
}
type FooStructForTimeTypeFailFormat struct {
TimeFoo time.Time `form:"time_foo" time_format:"2017-11-15"`
}
type FooStructForTimeTypeFailLocation struct {
TimeFoo time.Time `form:"time_foo" time_format:"2006-01-02" time_location:"/asia/chong | t:"unix"`
UnixMilliTime time.Time `form:"unixMilliTime" time_format:"unixMilli"`
UnixMicroTime time.Time `form:"unixMicroTime" time_format:"unixMicro"`
}
type FooStructForTimeTypeNotFormat struct {
TimeFoo time.Time `form:"ti | {
"filepath": "binding/binding_test.go",
"language": "go",
"file_size": 39518,
"cut_index": 2151,
"middle_length": 229
} |
style
// license that can be found in the LICENSE file.
package binding
import (
"errors"
"testing"
)
func TestSliceValidationError(t *testing.T) {
tests := []struct {
name string
err SliceValidationError
want string
}{
{"has nil elements", SliceValidationError{errors.New("test error"), nil}, "[0]: test... | rs.New("second error"),
nil,
nil,
nil,
errors.New("last error"),
},
"[0]: first error\n[1]: second error\n[5]: last error",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.err.Error(); got != | liceValidationError{
errors.New("first error"),
errors.New("second error"),
},
"[0]: first error\n[1]: second error",
},
{
"has many elements",
SliceValidationError{
errors.New("first error"),
erro | {
"filepath": "binding/default_validator_test.go",
"language": "go",
"file_size": 3591,
"cut_index": 614,
"middle_length": 229
} |
2014 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package binding
import (
"errors"
"net/http"
)
const defaultMemory = 32 << 20
type (
formBinding struct{}
formPostBinding struct{}
formMultipar... | ) Name() string {
return "form-urlencoded"
}
func (formPostBinding) Bind(req *http.Request, obj any) error {
if err := req.ParseForm(); err != nil {
return err
}
if err := mapForm(obj, req.PostForm); err != nil {
return err
}
return validate(obj | if err := req.ParseMultipartForm(defaultMemory); err != nil && !errors.Is(err, http.ErrNotMultipart) {
return err
}
if err := mapForm(obj, req.Form); err != nil {
return err
}
return validate(obj)
}
func (formPostBinding | {
"filepath": "binding/form.go",
"language": "go",
"file_size": 1357,
"cut_index": 524,
"middle_length": 229
} |
.New("unknown type")
// ErrConvertMapStringSlice can not convert to map[string][]string
ErrConvertMapStringSlice = errors.New("can not convert to map slices of strings")
// ErrConvertToMapString can not convert to map[string]string
ErrConvertToMapString = errors.New("can not convert to map of strings")
)
func ma... | if ptr is a map
ptrVal := reflect.ValueOf(ptr)
var pointed any
if ptrVal.Kind() == reflect.Ptr {
ptrVal = ptrVal.Elem()
pointed = ptrVal.Interface()
}
if ptrVal.Kind() == reflect.Map &&
ptrVal.Type().Key().Kind() == reflect.String {
if pointed | ormWithTag(ptr any, form map[string][]string, tag string) error {
return mapFormByTag(ptr, form, tag)
}
var emptyField = reflect.StructField{}
func mapFormByTag(ptr any, form map[string][]string, tag string) error {
// Check | {
"filepath": "binding/form_mapping.go",
"language": "go",
"file_size": 13602,
"cut_index": 921,
"middle_length": 229
} |
style
// license that can be found in the LICENSE file.
//go:build nomsgpack
package binding
import "net/http"
// Content-Type MIME of the most common data formats.
const (
MIMEJSON = "application/json"
MIMEHTML = "text/html"
MIMEXML = "application/xml"
MIMEXML2 ... | terface which needs to be implemented for binding the
// data present in the request such as JSON request body, query parameters or
// the form POST.
type Binding interface {
Name() string
Bind(*http.Request, any) error
}
// BindingBody adds BindBody me | lication/x-protobuf"
MIMEYAML = "application/x-yaml"
MIMEYAML2 = "application/yaml"
MIMETOML = "application/toml"
MIMEBSON = "application/bson"
)
// Binding describes the in | {
"filepath": "binding/binding_nomsgpack.go",
"language": "go",
"file_size": 3822,
"cut_index": 614,
"middle_length": 229
} |
reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package binding
import (
"reflect"
"strconv"
"strings"
"sync"
"github.com/go-playground/validator/v10"
)
type defaultValidator struct {
once sync.Once
validate *validator.Validate
}
type Sl... | ing()
}
var _ StructValidator = (*defaultValidator)(nil)
// ValidateStruct receives any kind of type, but only performed struct or pointer to struct type.
func (v *defaultValidator) ValidateStruct(obj any) error {
if obj == nil {
return nil
}
value | == 0 {
return ""
}
var b strings.Builder
for i := range len(err) {
if err[i] != nil {
if b.Len() > 0 {
b.WriteString("\n")
}
b.WriteString("[" + strconv.Itoa(i) + "]: " + err[i].Error())
}
}
return b.Str | {
"filepath": "binding/default_validator.go",
"language": "go",
"file_size": 2294,
"cut_index": 563,
"middle_length": 229
} |
ader }{}, "", &multipart.FileHeader{}},
} {
tp := reflect.TypeOf(tt.value)
testName := tt.name + ":" + tp.Field(0).Type.String()
val := reflect.New(reflect.TypeOf(tt.value))
val.Elem().Set(reflect.ValueOf(tt.value))
field := val.Elem().Type().Field(0)
_, err := mapping(val, emptyField, formSource{field.... | re.NoError(t, err)
assert.Equal(t, "defaultVal", s.Str)
assert.Equal(t, 9, s.Int)
assert.Equal(t, []int{9}, s.Slice)
assert.Equal(t, [1]int{9}, s.Array)
}
func TestMappingSkipField(t *testing.T) {
var s struct {
A int
}
err := mappingByPtr(&s, f | ng.T) {
var s struct {
Str string `form:",default=defaultVal"`
Int int `form:",default=9"`
Slice []int `form:",default=9"`
Array [1]int `form:",default=9"`
}
err := mappingByPtr(&s, formSource{}, "form")
requi | {
"filepath": "binding/form_mapping_test.go",
"language": "go",
"file_size": 34152,
"cut_index": 2151,
"middle_length": 229
} |
erved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package binding
import (
"net/http"
"net/textproto"
"reflect"
)
type headerBinding struct{}
func (headerBinding) Name() string {
return "header"
}
func (headerBinding) Bind(req *http.Request, obj any)... | ]string
var _ setter = headerSource(nil)
func (hs headerSource) TrySet(value reflect.Value, field reflect.StructField, tagValue string, opt setOptions) (bool, error) {
return setByForm(value, field, hs, textproto.CanonicalMIMEHeaderKey(tagValue), opt)
} | urce(h), "header")
}
type headerSource map[string][ | {
"filepath": "binding/header.go",
"language": "go",
"file_size": 868,
"cut_index": 559,
"middle_length": 52
} |
tptest"
"testing"
"time"
"unsafe"
"github.com/gin-gonic/gin/codec/json"
"github.com/gin-gonic/gin/render"
jsoniter "github.com/json-iterator/go"
"github.com/modern-go/reflect2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestJSONBindingBindBody(t *testing.T) {
var s str... | llo"])
}
func TestCustomJsonCodec(t *testing.T) {
// Restore json encoding configuration after testing
oldMarshal := json.API
defer func() {
json.API = oldMarshal
}()
// Custom json api
json.API = customJsonApi{}
// test decode json
obj := cust | sting.T) {
s := make(map[string]string)
err := jsonBinding{}.BindBody([]byte(`{"foo": "FOO","hello":"world"}`), &s)
require.NoError(t, err)
assert.Len(t, s, 2)
assert.Equal(t, "FOO", s["foo"])
assert.Equal(t, "world", s["he | {
"filepath": "binding/json_test.go",
"language": "go",
"file_size": 5524,
"cut_index": 716,
"middle_length": 229
} |
/ Copyright 2019 Gin Core Team. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
//go:build !nomsgpack
package binding
import (
"bytes"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/ug... | "}), &s)
require.NoError(t, err)
assert.Equal(t, "FOO", s.Foo)
}
func msgpackBody(t *testing.T, obj any) []byte {
var bs bytes.Buffer
h := &codec.MsgpackHandle{}
err := codec.NewEncoder(&bs, h).Encode(obj)
require.NoError(t, err)
return bs.Bytes()
| eststruct{"FOO | {
"filepath": "binding/msgpack_test.go",
"language": "go",
"file_size": 785,
"cut_index": 513,
"middle_length": 14
} |
style
// license that can be found in the LICENSE file.
package binding
import (
"bytes"
"io"
"mime/multipart"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestFormMultipartBindingBindOneFile(t *testing.T) {
var s struct {
FileValue multipart.Fil... | q, &s)
require.NoError(t, err)
assertMultipartFileHeader(t, &s.FileValue, file)
assertMultipartFileHeader(t, s.FilePtr, file)
assert.Len(t, s.SliceValues, 1)
assertMultipartFileHeader(t, &s.SliceValues[0], file)
assert.Len(t, s.SlicePtrs, 1)
assert | Values [1]multipart.FileHeader `form:"file"`
ArrayPtrs [1]*multipart.FileHeader `form:"file"`
}
file := testFile{"file", "file1", []byte("hello")}
req := createRequestMultipartFiles(t, file)
err := FormMultipart.Bind(re | {
"filepath": "binding/multipart_form_mapping_test.go",
"language": "go",
"file_size": 3794,
"cut_index": 614,
"middle_length": 229
} |
testing"
"time"
"github.com/go-playground/validator/v10"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type testInterface interface {
String() string
}
type substructNoValidation struct {
IString string
IInt int
}
type mapNoValidationSub map[string]substructNoValidation
typ... | IntSlice []int
IntPointerSlice []*int
StructPointerSlice []*substructNoValidation
StructSlice []substructNoValidation
InterfaceSlice []testInterface
UniversalInterface any
CustomInterface testInterface
FloatMap map[str | int8
Uinteger16 uint16
Uinteger32 uint32
Uinteger64 uint64
Float32 float32
Float64 float64
String string
Date time.Time
Struct substructNoValidation
InlinedStruct struct {
String []string
Integer int
}
| {
"filepath": "binding/validate_test.go",
"language": "go",
"file_size": 6125,
"cut_index": 716,
"middle_length": 229
} |
rtinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package binding
import (
"bytes"
"errors"
"io"
"net/http"
"github.com/gin-gonic/gin/codec/json"
)
// EnableDecoderUseNumber is used to call the UseNumber method on the JS... | h do not match any non-ignored, exported fields in the destination.
var EnableDecoderDisallowUnknownFields = false
type jsonBinding struct{}
func (jsonBinding) Name() string {
return "json"
}
func (jsonBinding) Bind(req *http.Request, obj any) error {
| wnFields is used to call the DisallowUnknownFields method
// on the JSON Decoder instance. DisallowUnknownFields causes the Decoder to
// return an error when the destination is a struct and the input contains object
// keys whic | {
"filepath": "binding/json.go",
"language": "go",
"file_size": 1543,
"cut_index": 537,
"middle_length": 229
} |
d.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package binding
import (
"errors"
"mime/multipart"
"net/http"
"reflect"
)
type multipartRequest http.Request
var _ setter = (*multipartRequest)(nil)
var (
// ErrMultiFileHeader multipart.FileHeader inval... | t.StructField, key string, opt setOptions) (bool, error) {
if files := r.MultipartForm.File[key]; len(files) != 0 {
return setByMultipartFormFile(value, field, files)
}
return setByForm(value, field, r.MultipartForm.Value, key, opt)
}
func setByMult | alid = errors.New("unsupported len of array for []*multipart.FileHeader")
)
// TrySet tries to set a value by the multipart request with the binding a form file
func (r *multipartRequest) TrySet(value reflect.Value, field reflec | {
"filepath": "binding/multipart_form_mapping.go",
"language": "go",
"file_size": 2244,
"cut_index": 563,
"middle_length": 229
} |
verned by a MIT style
// license that can be found in the LICENSE file.
package binding
import (
"errors"
"io"
"net/http"
"google.golang.org/protobuf/proto"
)
type protobufBinding struct{}
func (protobufBinding) Name() string {
return "protobuf"
}
func (b protobufBinding) Bind(req *http.Request, obj any) err... | oMessage")
}
if err := proto.Unmarshal(body, msg); err != nil {
return err
}
// Here it's same to return validate(obj), but until now we can't add
// `binding:""` to the struct which automatically generate by gen-proto
return nil
// return validat | sage)
if !ok {
return errors.New("obj is not Prot | {
"filepath": "binding/protobuf.go",
"language": "go",
"file_size": 923,
"cut_index": 606,
"middle_length": 52
} |
e Team. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package json
import "io"
// API the json codec in use.
var API Core
// Core the api for json codec.
type Core interface {
Marshal(v any) ([]byte, error)
Unmarshal(data []byte, v any... | nd \u003e
// to avoid certain safety problems that can arise when embedding JSON in HTML.
//
// In non-HTML settings where the escaping interferes with the readability
// of the output, SetEscapeHTML(false) disables this behavior.
SetEscapeHTML(on boo | o an output stream.
type Encoder interface {
// SetEscapeHTML specifies whether problematic HTML characters
// should be escaped inside JSON quoted strings.
// The default behavior is to escape &, <, and > to \u0026, \u003c, a | {
"filepath": "codec/json/api.go",
"language": "go",
"file_size": 1942,
"cut_index": 537,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.