repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/docker/build_test.go
dive/image/docker/build_test.go
package docker import ( "github.com/stretchr/testify/require" "path/filepath" "testing" "github.com/spf13/afero" "github.com/stretchr/testify/assert" ) func TestIsFileFlagsAreSet(t *testing.T) { tests := []struct { name string args []string flags []string expected bool }{ { name: "flag present in the middle with value", args: []string{"arg1", "-f", "dockerfile", "arg2"}, flags: []string{"-f"}, expected: true, }, { name: "flag present at the beginning with value", args: []string{"-f", "dockerfile", "arg1", "arg2"}, flags: []string{"-f"}, expected: true, }, { name: "flag present at the end with no value", args: []string{"arg1", "arg2", "-f"}, flags: []string{"-f"}, expected: false, }, { name: "flag not present", args: []string{"arg1", "arg2", "arg3"}, flags: []string{"-f"}, expected: false, }, { name: "one of multiple flags present", args: []string{"arg1", "--file", "dockerfile", "arg2"}, flags: []string{"-f", "--file"}, expected: true, }, { name: "none of multiple flags present", args: []string{"arg1", "-x", "value", "arg2"}, flags: []string{"-f", "--file"}, expected: false, }, { name: "empty args", args: []string{}, flags: []string{"-f", "--file"}, expected: false, }, { name: "empty flags", args: []string{"arg1", "-f", "value"}, flags: []string{}, expected: false, }, { name: "flag with multiple values", args: []string{"arg1", "-f", "value1", "value2"}, flags: []string{"-f"}, expected: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := isFileFlagsAreSet(tt.args, tt.flags...) assert.Equal(t, tt.expected, result, "isFileFlagsAreSet() = %v, want %v", result, tt.expected) }) } } func TestTryFindContainerfile(t *testing.T) { tests := []struct { name string buildArgs []string setupFs func(t testing.TB, fs afero.Fs) expectedPath string expectedErrMsg string }{ { name: "find Containerfile (uppercase)", buildArgs: []string{"testdir"}, setupFs: func(t testing.TB, fs afero.Fs) { create(t, fs, "testdir/Containerfile", "FROM alpine") }, expectedPath: filepath.Join("testdir", "Containerfile"), expectedErrMsg: "", }, { name: "find containerfile (lowercase)", buildArgs: []string{"testdir"}, setupFs: func(t testing.TB, fs afero.Fs) { create(t, fs, "testdir/containerfile", "FROM alpine") }, expectedPath: filepath.Join("testdir", "containerfile"), expectedErrMsg: "", }, { name: "find Dockerfile when no Containerfile exists", buildArgs: []string{"testdir"}, setupFs: func(t testing.TB, fs afero.Fs) { create(t, fs, "testdir/Dockerfile", "FROM alpine") }, expectedPath: filepath.Join("testdir", "Dockerfile"), expectedErrMsg: "", }, { name: "find dockerfile (lowercase)", buildArgs: []string{"testdir"}, setupFs: func(t testing.TB, fs afero.Fs) { create(t, fs, "testdir/dockerfile", "FROM alpine") }, expectedPath: filepath.Join("testdir", "dockerfile"), expectedErrMsg: "", }, { name: "prefer Containerfile over Dockerfile", buildArgs: []string{"testdir"}, setupFs: func(t testing.TB, fs afero.Fs) { create(t, fs, "testdir/Containerfile", "FROM alpine") create(t, fs, "testdir/Dockerfile", "FROM ubuntu") }, expectedPath: filepath.Join("testdir", "Containerfile"), expectedErrMsg: "", }, { name: "non-existent directory", buildArgs: []string{"nonexistentdir"}, setupFs: func(t testing.TB, fs afero.Fs) {}, expectedPath: "", expectedErrMsg: "could not find Containerfile or Dockerfile", }, { name: "empty build args", buildArgs: []string{}, setupFs: func(t testing.TB, fs afero.Fs) {}, expectedPath: "", expectedErrMsg: "could not find Containerfile or Dockerfile", }, { name: "directory exists but no container files", buildArgs: []string{"testdir"}, setupFs: func(t testing.TB, fs afero.Fs) { create(t, fs, "testdir/somefile.txt", "content") }, expectedPath: "", expectedErrMsg: "could not find Containerfile or Dockerfile", }, { name: "find in second directory", buildArgs: []string{"firstdir", "seconddir"}, setupFs: func(t testing.TB, fs afero.Fs) { err := fs.MkdirAll("firstdir", 0755) require.NoError(t, err, "Failed to create directory: firstdir") create(t, fs, "seconddir/Dockerfile", "FROM alpine") }, expectedPath: filepath.Join("seconddir", "Dockerfile"), expectedErrMsg: "", }, { name: "find in first directory when both have files", buildArgs: []string{"firstdir", "seconddir"}, setupFs: func(t testing.TB, fs afero.Fs) { create(t, fs, "firstdir/Containerfile", "FROM alpine") create(t, fs, "seconddir/Dockerfile", "FROM ubuntu") }, expectedPath: filepath.Join("firstdir", "Containerfile"), expectedErrMsg: "", }, { name: "file argument not a directory", buildArgs: []string{"testfile.txt"}, setupFs: func(t testing.TB, fs afero.Fs) { create(t, fs, "testfile.txt", "content") }, expectedPath: "", expectedErrMsg: "could not find Containerfile or Dockerfile", }, { name: "mixed args with valid directory", buildArgs: []string{"testfile.txt", "testdir"}, setupFs: func(t testing.TB, fs afero.Fs) { create(t, fs, "testfile.txt", "content") create(t, fs, "testdir/Dockerfile", "FROM alpine") }, expectedPath: filepath.Join("testdir", "Dockerfile"), expectedErrMsg: "", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { fs := afero.NewMemMapFs() tt.setupFs(t, fs) result, err := tryFindContainerfile(fs, tt.buildArgs) if tt.expectedErrMsg != "" { assert.Error(t, err) assert.Contains(t, err.Error(), tt.expectedErrMsg) } else { assert.NoError(t, err) assert.Equal(t, tt.expectedPath, result) } }) } } func create(t testing.TB, fs afero.Fs, path, contents string) { t.Helper() dir := filepath.Dir(path) if dir != "." { err := fs.MkdirAll(dir, 0755) require.NoError(t, err, "Failed to create directory: %s", dir) } err := afero.WriteFile(fs, path, []byte(contents), 0644) require.NoError(t, err, "Failed to write file: %s", path) }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/docker/archive_resolver.go
dive/image/docker/archive_resolver.go
package docker import ( "context" "fmt" "os" "github.com/wagoodman/dive/dive/image" ) type archiveResolver struct{} func NewResolverFromArchive() *archiveResolver { return &archiveResolver{} } // Name returns the name of the resolver to display to the user. func (r *archiveResolver) Name() string { return "docker-archive" } func (r *archiveResolver) Fetch(ctx context.Context, path string) (*image.Image, error) { reader, err := os.Open(path) if err != nil { return nil, err } defer reader.Close() img, err := NewImageArchive(reader) if err != nil { return nil, err } return img.ToImage(path) } func (r *archiveResolver) Build(ctx context.Context, args []string) (*image.Image, error) { return nil, fmt.Errorf("build option not supported for docker archive resolver") } func (r *archiveResolver) Extract(ctx context.Context, id string, l string, p string) error { return fmt.Errorf("not implemented") }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/podman/resolver_unsupported.go
dive/image/podman/resolver_unsupported.go
//go:build !linux && !darwin // +build !linux,!darwin package podman import ( "context" "fmt" "github.com/wagoodman/dive/dive/image" ) type resolver struct{} func NewResolverFromEngine() *resolver { return &resolver{} } // Name returns the name of the resolver to display to the user. func (r *resolver) Name() string { return "podman" } func (r *resolver) Build(ctx context.Context, args []string) (*image.Image, error) { return nil, fmt.Errorf("unsupported platform") } func (r *resolver) Fetch(ctx context.Context, id string) (*image.Image, error) { return nil, fmt.Errorf("unsupported platform") } func (r *resolver) Extract(ctx context.Context, id string, l string, p string) error { return fmt.Errorf("unsupported platform") }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/podman/resolver.go
dive/image/podman/resolver.go
//go:build linux || darwin package podman import ( "context" "fmt" "io" "github.com/wagoodman/dive/dive/image" "github.com/wagoodman/dive/dive/image/docker" ) type resolver struct{} func NewResolverFromEngine() *resolver { return &resolver{} } // Name returns the name of the resolver to display to the user. func (r *resolver) Name() string { return "podman" } func (r *resolver) Build(ctx context.Context, args []string) (*image.Image, error) { id, err := buildImageFromCli(args) if err != nil { return nil, err } return r.Fetch(ctx, id) } func (r *resolver) Fetch(ctx context.Context, id string) (*image.Image, error) { // todo: add podman fetch attempt via varlink first... img, err := r.resolveFromDockerArchive(id) if err == nil { return img, err } return nil, fmt.Errorf("unable to resolve image %q: %+v", id, err) } func (r *resolver) Extract(ctx context.Context, id string, l string, p string) error { // todo: add podman fetch attempt via varlink first... err, reader := streamPodmanCmd("image", "save", id) if err != nil { return err } if err := docker.ExtractFromImage(io.NopCloser(reader), l, p); err == nil { return nil } return fmt.Errorf("unable to extract from image %q: %+v", id, err) } func (r *resolver) resolveFromDockerArchive(id string) (*image.Image, error) { err, reader := streamPodmanCmd("image", "save", id) if err != nil { return nil, err } img, err := docker.NewImageArchive(io.NopCloser(reader)) if err != nil { return nil, err } return img.ToImage(id) }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/podman/build.go
dive/image/podman/build.go
//go:build linux || darwin package podman import ( "os" ) func buildImageFromCli(buildArgs []string) (string, error) { iidfile, err := os.CreateTemp("/tmp", "dive.*.iid") if err != nil { return "", err } defer os.Remove(iidfile.Name()) defer iidfile.Close() allArgs := append([]string{"--iidfile", iidfile.Name()}, buildArgs...) err = runPodmanCmd("build", allArgs...) if err != nil { return "", err } imageId, err := os.ReadFile(iidfile.Name()) if err != nil { return "", err } return string(imageId), nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/podman/cli.go
dive/image/podman/cli.go
//go:build linux || darwin package podman import ( "fmt" "github.com/wagoodman/dive/internal/log" "github.com/wagoodman/dive/internal/utils" "io" "os" "os/exec" "strings" ) // runPodmanCmd runs a given Podman command in the current tty func runPodmanCmd(cmdStr string, args ...string) error { if !isPodmanClientBinaryAvailable() { return fmt.Errorf("cannot find podman client executable") } allArgs := utils.CleanArgs(append([]string{cmdStr}, args...)) fullCmd := strings.Join(append([]string{"docker"}, allArgs...), " ") log.WithFields("cmd", fullCmd).Trace("executing") cmd := exec.Command("podman", allArgs...) cmd.Env = os.Environ() cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Stdin = os.Stdin return cmd.Run() } func streamPodmanCmd(args ...string) (error, io.Reader) { if !isPodmanClientBinaryAvailable() { return fmt.Errorf("cannot find podman client executable"), nil } allArgs := utils.CleanArgs(args) fullCmd := strings.Join(append([]string{"docker"}, allArgs...), " ") log.WithFields("cmd", fullCmd).Trace("executing (streaming)") cmd := exec.Command("podman", allArgs...) cmd.Env = os.Environ() reader, writer, err := os.Pipe() if err != nil { return err, nil } defer writer.Close() cmd.Stdout = writer cmd.Stderr = os.Stderr return cmd.Start(), reader } func isPodmanClientBinaryAvailable() bool { _, err := exec.LookPath("podman") return err == nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/filetree/node_data_test.go
dive/filetree/node_data_test.go
package filetree import ( "testing" ) func TestAssignDiffType(t *testing.T) { tree := NewFileTree() node, _, err := tree.AddPath("/usr", *BlankFileChangeInfo("/usr")) if err != nil { t.Errorf("Expected no error from fetching path. got: %v", err) } node.Data.DiffType = Modified if tree.Root.Children["usr"].Data.DiffType != Modified { t.Fail() } } func TestMergeDiffTypes(t *testing.T) { a := Unmodified b := Unmodified merged := a.merge(b) if merged != Unmodified { t.Errorf("Expected Unchanged (0) but got %v", merged) } a = Modified b = Unmodified merged = a.merge(b) if merged != Modified { t.Errorf("Expected Unchanged (0) but got %v", merged) } } func BlankFileChangeInfo(path string) (f *FileInfo) { result := FileInfo{ Path: path, TypeFlag: 1, hash: 123, } return &result }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/filetree/file_info.go
dive/filetree/file_info.go
package filetree import ( "archive/tar" "fmt" "io" "os" "github.com/cespare/xxhash/v2" ) // FileInfo contains tar metadata for a specific FileNode type FileInfo struct { Path string `json:"path"` TypeFlag byte `json:"typeFlag"` Linkname string `json:"linkName"` hash uint64 //`json:"hash"` Size int64 `json:"size"` Mode os.FileMode `json:"fileMode"` Uid int `json:"uid"` Gid int `json:"gid"` IsDir bool `json:"isDir"` } // NewFileInfoFromTarHeader extracts the metadata from a tar header and file contents and generates a new FileInfo object. func NewFileInfoFromTarHeader(reader *tar.Reader, header *tar.Header, path string) FileInfo { var hash uint64 if header.Typeflag != tar.TypeDir { hash = getHashFromReader(reader) } return FileInfo{ Path: path, TypeFlag: header.Typeflag, Linkname: header.Linkname, hash: hash, Size: header.FileInfo().Size(), Mode: header.FileInfo().Mode(), Uid: header.Uid, Gid: header.Gid, IsDir: header.FileInfo().IsDir(), } } func NewFileInfo(realPath, path string, info os.FileInfo) FileInfo { var err error // todo: don't use tar types here, create our own... var fileType byte var linkName string var size int64 if info.Mode()&os.ModeSymlink != 0 { fileType = tar.TypeSymlink linkName, err = os.Readlink(realPath) if err != nil { panic(fmt.Errorf("unable to read symlink %q: %s", realPath, err)) } } else if info.IsDir() { fileType = tar.TypeDir } else { fileType = tar.TypeReg size = info.Size() } var hash uint64 if fileType != tar.TypeDir { file, err := os.Open(realPath) if err != nil { panic(fmt.Errorf("unable to open file %q: %s", realPath, err)) } defer file.Close() hash = getHashFromReader(file) } return FileInfo{ Path: path, TypeFlag: fileType, Linkname: linkName, hash: hash, Size: size, Mode: info.Mode(), // todo: support UID/GID Uid: -1, Gid: -1, IsDir: info.IsDir(), } } // Copy duplicates a FileInfo func (data *FileInfo) Copy() *FileInfo { if data == nil { return nil } return &FileInfo{ Path: data.Path, TypeFlag: data.TypeFlag, Linkname: data.Linkname, hash: data.hash, Size: data.Size, Mode: data.Mode, Uid: data.Uid, Gid: data.Gid, IsDir: data.IsDir, } } // Compare determines the DiffType between two FileInfos based on the type and contents of each given FileInfo func (data *FileInfo) Compare(other FileInfo) DiffType { if data.TypeFlag == other.TypeFlag { if data.hash == other.hash && data.Mode == other.Mode && data.Uid == other.Uid && data.Gid == other.Gid { return Unmodified } } return Modified } func getHashFromReader(reader io.Reader) uint64 { h := xxhash.New() buf := make([]byte, 1024) for { n, err := reader.Read(buf) if err != nil && err != io.EOF { panic(fmt.Errorf("unable to read file: %w", err)) } if n == 0 { break } _, err = h.Write(buf[:n]) if err != nil { panic(fmt.Errorf("unable to write to hash: %w", err)) } } return h.Sum64() }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/filetree/file_tree_test.go
dive/filetree/file_tree_test.go
package filetree import ( "fmt" "github.com/stretchr/testify/assert" "testing" ) func stringInSlice(a string, list []string) bool { for _, b := range list { if b == a { return true } } return false } func AssertDiffType(node *FileNode, expectedDiffType DiffType) error { if node.Data.DiffType != expectedDiffType { return fmt.Errorf("Expecting node at %s to have DiffType %v, but had %v", node.Path(), expectedDiffType, node.Data.DiffType) } return nil } func TestStringCollapsed(t *testing.T) { tree := NewFileTree() tree.Root.AddChild("1 node!", FileInfo{}) two := tree.Root.AddChild("2 node!", FileInfo{}) subTwo := two.AddChild("2 child!", FileInfo{}) subTwo.AddChild("2 grandchild!", FileInfo{}) subTwo.Data.ViewInfo.Collapsed = true three := tree.Root.AddChild("3 node!", FileInfo{}) subThree := three.AddChild("3 child!", FileInfo{}) three.AddChild("3 nested child 1!", FileInfo{}) threeGc1 := subThree.AddChild("3 grandchild 1!", FileInfo{}) threeGc1.AddChild("3 greatgrandchild 1!", FileInfo{}) subThree.AddChild("3 grandchild 2!", FileInfo{}) four := tree.Root.AddChild("4 node!", FileInfo{}) four.Data.ViewInfo.Collapsed = true tree.Root.AddChild("5 node!", FileInfo{}) four.AddChild("6, one level down...", FileInfo{}) expected := `β”œβ”€β”€ 1 node! β”œβ”€β”€ 2 node! β”‚ β””β”€βŠ• 2 child! β”œβ”€β”€ 3 node! β”‚ β”œβ”€β”€ 3 child! β”‚ β”‚ β”œβ”€β”€ 3 grandchild 1! β”‚ β”‚ β”‚ └── 3 greatgrandchild 1! β”‚ β”‚ └── 3 grandchild 2! β”‚ └── 3 nested child 1! β”œβ”€βŠ• 4 node! └── 5 node! ` actual := tree.String(false) if expected != actual { t.Errorf("Expected tree string:\n--->%s<---\nGot:\n--->%s<---", expected, actual) } } func TestString(t *testing.T) { tree := NewFileTree() tree.Root.AddChild("1 node!", FileInfo{}) tree.Root.AddChild("2 node!", FileInfo{}) tree.Root.AddChild("3 node!", FileInfo{}) four := tree.Root.AddChild("4 node!", FileInfo{}) tree.Root.AddChild("5 node!", FileInfo{}) four.AddChild("6, one level down...", FileInfo{}) expected := `β”œβ”€β”€ 1 node! β”œβ”€β”€ 2 node! β”œβ”€β”€ 3 node! β”œβ”€β”€ 4 node! β”‚ └── 6, one level down... └── 5 node! ` actual := tree.String(false) if expected != actual { t.Errorf("Expected tree string:\n--->%s<---\nGot:\n--->%s<---", expected, actual) } } func TestStringBetween(t *testing.T) { tree := NewFileTree() _, _, err := tree.AddPath("/etc/nginx/nginx.conf", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/etc/nginx/public", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/var/run/systemd", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/var/run/bashful", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/tmp", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/tmp/nonsense", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } expected := `β”‚ └── public β”œβ”€β”€ tmp β”‚ └── nonsense ` actual := tree.StringBetween(3, 5, false) if expected != actual { t.Errorf("Expected tree string:\n--->%s<---\nGot:\n--->%s<---", expected, actual) } } func TestRejectPurelyRelativePath(t *testing.T) { tree := NewFileTree() _, _, err := tree.AddPath("./etc/nginx/nginx.conf", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("./", FileInfo{}) if err == nil { t.Errorf("expected to reject relative path, but did not") } } func TestAddRelativePath(t *testing.T) { tree := NewFileTree() _, _, err := tree.AddPath("./etc/nginx/nginx.conf", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } expected := `└── etc └── nginx └── nginx.conf ` actual := tree.String(false) if expected != actual { t.Errorf("Expected tree string:\n--->%s<---\nGot:\n--->%s<---", expected, actual) } } func TestAddPath(t *testing.T) { tree := NewFileTree() _, _, err := tree.AddPath("/etc/nginx/nginx.conf", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/etc/nginx/public", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/var/run/systemd", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/var/run/bashful", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/tmp", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/tmp/nonsense", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } expected := `β”œβ”€β”€ etc β”‚ └── nginx β”‚ β”œβ”€β”€ nginx.conf β”‚ └── public β”œβ”€β”€ tmp β”‚ └── nonsense └── var └── run β”œβ”€β”€ bashful └── systemd ` actual := tree.String(false) if expected != actual { t.Errorf("Expected tree string:\n--->%s<---\nGot:\n--->%s<---", expected, actual) } } func TestAddWhiteoutPath(t *testing.T) { tree := NewFileTree() node, _, err := tree.AddPath("usr/local/lib/python3.7/site-packages/pip/.wh..wh..opq", FileInfo{}) if err != nil { t.Errorf("expected no error but got: %v", err) } if node != nil { t.Errorf("expected node to be nil, but got: %v", node) } expected := `└── usr └── local └── lib └── python3.7 └── site-packages └── pip ` actual := tree.String(false) if expected != actual { t.Errorf("Expected tree string:\n--->%s<---\nGot:\n--->%s<---", expected, actual) } } func TestRemovePath(t *testing.T) { tree := NewFileTree() _, _, err := tree.AddPath("/etc/nginx/nginx.conf", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/etc/nginx/public", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/var/run/systemd", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/var/run/bashful", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/tmp", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/tmp/nonsense", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } err = tree.RemovePath("/var/run/bashful") if err != nil { t.Errorf("could not setup test: %v", err) } err = tree.RemovePath("/tmp") if err != nil { t.Errorf("could not setup test: %v", err) } expected := `β”œβ”€β”€ etc β”‚ └── nginx β”‚ β”œβ”€β”€ nginx.conf β”‚ └── public └── var └── run └── systemd ` actual := tree.String(false) if expected != actual { t.Errorf("Expected tree string:\n--->%s<---\nGot:\n--->%s<---", expected, actual) } } func TestStack(t *testing.T) { payloadKey := "/var/run/systemd" payloadValue := FileInfo{ Path: "yup", } tree1 := NewFileTree() _, _, err := tree1.AddPath("/etc/nginx/public", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree1.AddPath(payloadKey, FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree1.AddPath("/var/run/bashful", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree1.AddPath("/tmp", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree1.AddPath("/tmp/nonsense", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } tree2 := NewFileTree() // add new files _, _, err = tree2.AddPath("/etc/nginx/nginx.conf", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } // modify current files _, _, err = tree2.AddPath(payloadKey, payloadValue) if err != nil { t.Errorf("could not setup test: %v", err) } // whiteout the following files _, _, err = tree2.AddPath("/var/run/.wh.bashful", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree2.AddPath("/.wh.tmp", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } // ignore opaque whiteout files entirely node, _, err := tree2.AddPath("/.wh..wh..opq", FileInfo{}) if err != nil { t.Errorf("expected no error on whiteout file add, but got %v", err) } if node != nil { t.Errorf("expected no node on whiteout file add, but got %v", node) } failedPaths, err := tree1.Stack(tree2) if err != nil { t.Errorf("Could not stack refTrees: %v", err) } if len(failedPaths) > 0 { t.Errorf("expected no filepath errors, got %d", len(failedPaths)) } expected := `β”œβ”€β”€ etc β”‚ └── nginx β”‚ β”œβ”€β”€ nginx.conf β”‚ └── public └── var └── run └── systemd ` node, err = tree1.GetNode(payloadKey) if err != nil { t.Errorf("Expected '%s' to still exist, but it doesn't", payloadKey) } if node == nil || node.Data.FileInfo.Path != payloadValue.Path { t.Errorf("Expected '%s' value to be %+v but got %+v", payloadKey, payloadValue, node.Data.FileInfo) } actual := tree1.String(false) if expected != actual { t.Errorf("Expected tree string:\n--->%s<---\nGot:\n--->%s<---", expected, actual) } } func TestCopy(t *testing.T) { tree := NewFileTree() _, _, err := tree.AddPath("/etc/nginx/nginx.conf", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/etc/nginx/public", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/var/run/systemd", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/var/run/bashful", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/tmp", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/tmp/nonsense", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } err = tree.RemovePath("/var/run/bashful") if err != nil { t.Errorf("could not setup test: %v", err) } err = tree.RemovePath("/tmp") if err != nil { t.Errorf("could not setup test: %v", err) } expected := `β”œβ”€β”€ etc β”‚ └── nginx β”‚ β”œβ”€β”€ nginx.conf β”‚ └── public └── var └── run └── systemd ` NewFileTree := tree.Copy() actual := NewFileTree.String(false) if expected != actual { t.Errorf("Expected tree string:\n--->%s<---\nGot:\n--->%s<---", expected, actual) } } func TestCompareWithNoChanges(t *testing.T) { lowerTree := NewFileTree() upperTree := NewFileTree() paths := [...]string{"/etc", "/etc/sudoers", "/etc/hosts", "/usr/bin", "/usr/bin/bash", "/usr"} for _, value := range paths { fakeData := FileInfo{ Path: value, TypeFlag: 1, hash: 123, } _, _, err := lowerTree.AddPath(value, fakeData) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = upperTree.AddPath(value, fakeData) if err != nil { t.Errorf("could not setup test: %v", err) } } failedPaths, err := lowerTree.CompareAndMark(upperTree) if err != nil { t.Errorf("could not setup test: %v", err) } if len(failedPaths) > 0 { t.Errorf("expected no filepath errors, got %d", len(failedPaths)) } asserter := func(n *FileNode) error { if n.Path() == "/" { return nil } if (n.Data.DiffType) != Unmodified { t.Errorf("Expecting node at %s to have DiffType unchanged, but had %v", n.Path(), n.Data.DiffType) } return nil } err = lowerTree.VisitDepthChildFirst(asserter, nil) if err != nil { t.Error(err) } } func TestCompareWithAdds(t *testing.T) { lowerTree := NewFileTree() upperTree := NewFileTree() lowerPaths := [...]string{"/etc", "/etc/sudoers", "/usr", "/etc/hosts", "/usr/bin"} upperPaths := [...]string{"/etc", "/etc/sudoers", "/usr", "/etc/hosts", "/usr/bin", "/usr/bin/bash", "/a/new/path"} for _, value := range lowerPaths { _, _, err := lowerTree.AddPath(value, FileInfo{ Path: value, TypeFlag: 1, hash: 123, }) if err != nil { t.Errorf("could not setup test: %v", err) } } for _, value := range upperPaths { _, _, err := upperTree.AddPath(value, FileInfo{ Path: value, TypeFlag: 1, hash: 123, }) if err != nil { t.Errorf("could not setup test: %v", err) } } failedAssertions := []error{} failedPaths, err := lowerTree.CompareAndMark(upperTree) if err != nil { t.Errorf("Expected tree compare to have no errors, got: %v", err) } if len(failedPaths) > 0 { t.Errorf("expected no filepath errors, got %d", len(failedPaths)) } asserter := func(n *FileNode) error { p := n.Path() if p == "/" { return nil } else if stringInSlice(p, []string{"/usr/bin/bash", "/a", "/a/new", "/a/new/path"}) { if err := AssertDiffType(n, Added); err != nil { failedAssertions = append(failedAssertions, err) } } else if stringInSlice(p, []string{"/usr/bin", "/usr"}) { if err := AssertDiffType(n, Modified); err != nil { failedAssertions = append(failedAssertions, err) } } else { if err := AssertDiffType(n, Unmodified); err != nil { failedAssertions = append(failedAssertions, err) } } return nil } err = lowerTree.VisitDepthChildFirst(asserter, nil) if err != nil { t.Errorf("Expected no errors when visiting nodes, got: %+v", err) } if len(failedAssertions) > 0 { str := "\n" for _, value := range failedAssertions { str += fmt.Sprintf(" - %s\n", value.Error()) } t.Errorf("Expected no errors when evaluating nodes, got: %s", str) } } func TestCompareWithChanges(t *testing.T) { lowerTree := NewFileTree() upperTree := NewFileTree() changedPaths := []string{"/etc", "/usr", "/etc/hosts", "/etc/sudoers", "/usr/bin"} for _, value := range changedPaths { _, _, err := lowerTree.AddPath(value, FileInfo{ Path: value, TypeFlag: 1, hash: 123, }) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = upperTree.AddPath(value, FileInfo{ Path: value, TypeFlag: 1, hash: 456, }) if err != nil { t.Errorf("could not setup test: %v", err) } } chmodPath := "/etc/non-data-change" _, _, err := lowerTree.AddPath(chmodPath, FileInfo{ Path: chmodPath, TypeFlag: 1, hash: 123, Mode: 0, }) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = upperTree.AddPath(chmodPath, FileInfo{ Path: chmodPath, TypeFlag: 1, hash: 123, Mode: 1, }) if err != nil { t.Errorf("could not setup test: %v", err) } changedPaths = append(changedPaths, chmodPath) chownPath := "/etc/non-data-change-2" _, _, err = lowerTree.AddPath(chmodPath, FileInfo{ Path: chownPath, TypeFlag: 1, hash: 123, Mode: 1, Gid: 0, Uid: 0, }) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = upperTree.AddPath(chmodPath, FileInfo{ Path: chownPath, TypeFlag: 1, hash: 123, Mode: 1, Gid: 12, Uid: 12, }) if err != nil { t.Errorf("could not setup test: %v", err) } changedPaths = append(changedPaths, chownPath) failedPaths, err := lowerTree.CompareAndMark(upperTree) if err != nil { t.Errorf("unable to compare and mark: %+v", err) } if len(failedPaths) > 0 { t.Errorf("expected no filepath errors, got %d", len(failedPaths)) } failedAssertions := []error{} asserter := func(n *FileNode) error { p := n.Path() if p == "/" { return nil } else if stringInSlice(p, changedPaths) { if err := AssertDiffType(n, Modified); err != nil { failedAssertions = append(failedAssertions, err) } } else { if err := AssertDiffType(n, Unmodified); err != nil { failedAssertions = append(failedAssertions, err) } } return nil } err = lowerTree.VisitDepthChildFirst(asserter, nil) if err != nil { t.Errorf("Expected no errors when visiting nodes, got: %+v", err) } if len(failedAssertions) > 0 { str := "\n" for _, value := range failedAssertions { str += fmt.Sprintf(" - %s\n", value.Error()) } t.Errorf("Expected no errors when evaluating nodes, got: %s", str) } } func TestCompareWithRemoves(t *testing.T) { lowerTree := NewFileTree() upperTree := NewFileTree() lowerPaths := [...]string{"/etc", "/usr", "/etc/hosts", "/etc/sudoers", "/usr/bin", "/root", "/root/example", "/root/example/some1", "/root/example/some2"} upperPaths := [...]string{"/.wh.etc", "/usr", "/usr/.wh.bin", "/root/.wh.example"} for _, value := range lowerPaths { fakeData := FileInfo{ Path: value, TypeFlag: 1, hash: 123, } _, _, err := lowerTree.AddPath(value, fakeData) if err != nil { t.Errorf("could not setup test: %v", err) } } for _, value := range upperPaths { fakeData := FileInfo{ Path: value, TypeFlag: 1, hash: 123, } _, _, err := upperTree.AddPath(value, fakeData) if err != nil { t.Errorf("could not setup test: %v", err) } } failedPaths, err := lowerTree.CompareAndMark(upperTree) if err != nil { t.Errorf("could not setup test: %v", err) } if len(failedPaths) > 0 { t.Errorf("expected no filepath errors, got %d", len(failedPaths)) } failedAssertions := []error{} asserter := func(n *FileNode) error { p := n.Path() if p == "/" { return nil } else if stringInSlice(p, []string{"/etc", "/usr/bin", "/etc/hosts", "/etc/sudoers", "/root/example/some1", "/root/example/some2", "/root/example"}) { if err := AssertDiffType(n, Removed); err != nil { failedAssertions = append(failedAssertions, err) } } else if stringInSlice(p, []string{"/usr", "/root"}) { if err := AssertDiffType(n, Modified); err != nil { failedAssertions = append(failedAssertions, err) } } else { if err := AssertDiffType(n, Unmodified); err != nil { failedAssertions = append(failedAssertions, err) } } return nil } err = lowerTree.VisitDepthChildFirst(asserter, nil) if err != nil { t.Errorf("Expected no errors when visiting nodes, got: %+v", err) } if len(failedAssertions) > 0 { str := "\n" for _, value := range failedAssertions { str += fmt.Sprintf(" - %s\n", value.Error()) } t.Errorf("Expected no errors when evaluating nodes, got: %s", str) } } func TestStackRange(t *testing.T) { tree := NewFileTree() _, _, err := tree.AddPath("/etc/nginx/nginx.conf", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/etc/nginx/public", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/var/run/systemd", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/var/run/bashful", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/tmp", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } _, _, err = tree.AddPath("/tmp/nonsense", FileInfo{}) if err != nil { t.Errorf("could not setup test: %v", err) } err = tree.RemovePath("/var/run/bashful") if err != nil { t.Errorf("could not setup test: %v", err) } err = tree.RemovePath("/tmp") if err != nil { t.Errorf("could not setup test: %v", err) } lowerTree := NewFileTree() upperTree := NewFileTree() lowerPaths := [...]string{"/etc", "/usr", "/etc/hosts", "/etc/sudoers", "/usr/bin"} upperPaths := [...]string{"/etc", "/usr", "/etc/hosts", "/etc/sudoers", "/usr/bin"} for _, value := range lowerPaths { fakeData := FileInfo{ Path: value, TypeFlag: 1, hash: 123, } _, _, err = lowerTree.AddPath(value, fakeData) if err != nil { t.Errorf("could not setup test: %v", err) } } for _, value := range upperPaths { fakeData := FileInfo{ Path: value, TypeFlag: 1, hash: 456, } _, _, err = upperTree.AddPath(value, fakeData) if err != nil { t.Errorf("could not setup test: %v", err) } } trees := []*FileTree{lowerTree, upperTree, tree} _, failedPaths, err := StackTreeRange(trees, 0, 2) if len(failedPaths) > 0 { t.Errorf("expected no filepath errors, got %d", len(failedPaths)) } assert.NoError(t, err) } func TestRemoveOnIterate(t *testing.T) { tree := NewFileTree() paths := [...]string{"/etc", "/usr", "/etc/hosts", "/etc/sudoers", "/usr/bin", "/usr/something"} for _, value := range paths { fakeData := FileInfo{ Path: value, TypeFlag: 1, hash: 123, } node, _, err := tree.AddPath(value, fakeData) if err == nil && stringInSlice(node.Path(), []string{"/etc"}) { node.Data.ViewInfo.Hidden = true } } err := tree.VisitDepthChildFirst(func(node *FileNode) error { if node.Data.ViewInfo.Hidden { err := tree.RemovePath(node.Path()) if err != nil { t.Errorf("could not setup test: %v", err) } } return nil }, nil) if err != nil { t.Errorf("could not setup test: %v", err) } expected := `└── usr β”œβ”€β”€ bin └── something ` actual := tree.String(false) if expected != actual { t.Errorf("Expected tree string:\n--->%s<---\nGot:\n--->%s<---", expected, actual) } }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/filetree/node_data.go
dive/filetree/node_data.go
package filetree var GlobalFileTreeCollapse bool // NodeData is the payload for a FileNode type NodeData struct { ViewInfo ViewInfo FileInfo FileInfo `json:"fileInfo"` DiffType DiffType } // NewNodeData creates an empty NodeData struct for a FileNode func NewNodeData() *NodeData { return &NodeData{ ViewInfo: *NewViewInfo(), FileInfo: FileInfo{}, DiffType: Unmodified, } } // Copy duplicates a NodeData func (data *NodeData) Copy() *NodeData { return &NodeData{ ViewInfo: *data.ViewInfo.Copy(), FileInfo: *data.FileInfo.Copy(), DiffType: data.DiffType, } }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/filetree/file_node.go
dive/filetree/file_node.go
package filetree import ( "archive/tar" "fmt" "github.com/wagoodman/dive/internal/log" "strings" "github.com/dustin/go-humanize" "github.com/fatih/color" "github.com/phayes/permbits" ) const ( AttributeFormat = "%s%s %11s %10s " ) var diffTypeColor = map[DiffType]*color.Color{ Added: color.New(color.FgGreen), Removed: color.New(color.FgRed), Modified: color.New(color.FgYellow), Unmodified: color.New(color.Reset), } // FileNode represents a single file, its relation to files beneath it, the tree it exists in, and the metadata of the given file. type FileNode struct { Tree *FileTree Parent *FileNode Size int64 // memoized total size of file or directory Name string Data NodeData Children map[string]*FileNode path string } // NewNode creates a new FileNode relative to the given parent node with a payload. func NewNode(parent *FileNode, name string, data FileInfo) (node *FileNode) { node = new(FileNode) node.Name = name node.Data = *NewNodeData() node.Data.FileInfo = *data.Copy() node.Size = -1 // signal lazy load later node.Children = make(map[string]*FileNode) node.Parent = parent if parent != nil { node.Tree = parent.Tree } return node } // renderTreeLine returns a string representing this FileNode in the context of a greater ASCII tree. func (node *FileNode) renderTreeLine(spaces []bool, last bool, collapsed bool) string { var otherBranches string for _, space := range spaces { if space { otherBranches += noBranchSpace } else { otherBranches += branchSpace } } thisBranch := middleItem if last { thisBranch = lastItem } collapsedIndicator := uncollapsedItem if collapsed { collapsedIndicator = collapsedItem } return otherBranches + thisBranch + collapsedIndicator + node.String() + newLine } // Copy duplicates the existing node relative to a new parent node. func (node *FileNode) Copy(parent *FileNode) *FileNode { newNode := NewNode(parent, node.Name, node.Data.FileInfo) newNode.Data.ViewInfo = node.Data.ViewInfo newNode.Data.DiffType = node.Data.DiffType for name, child := range node.Children { newNode.Children[name] = child.Copy(newNode) child.Parent = newNode } return newNode } // AddChild creates a new node relative to the current FileNode. func (node *FileNode) AddChild(name string, data FileInfo) (child *FileNode) { // never allow processing of purely whiteout flag files (for now) if strings.HasPrefix(name, doubleWhiteoutPrefix) { return nil } child = NewNode(node, name, data) if node.Children[name] != nil { // tree node already exists, replace the payload, keep the children node.Children[name].Data.FileInfo = *data.Copy() } else { node.Children[name] = child node.Tree.Size++ } return child } // Remove deletes the current FileNode from it's parent FileNode's relations. func (node *FileNode) Remove() error { if node == node.Tree.Root { return fmt.Errorf("cannot remove the tree root") } for _, child := range node.Children { err := child.Remove() if err != nil { return err } } delete(node.Parent.Children, node.Name) node.Tree.Size-- return nil } // String shows the filename formatted into the proper color (by DiffType), additionally indicating if it is a symlink. func (node *FileNode) String() string { var display string if node == nil { return "" } display = node.Name if node.Data.FileInfo.TypeFlag == tar.TypeSymlink || node.Data.FileInfo.TypeFlag == tar.TypeLink { display += " β†’ " + node.Data.FileInfo.Linkname } return diffTypeColor[node.Data.DiffType].Sprint(display) } // MetadatString returns the FileNode metadata in a columnar string. func (node *FileNode) MetadataString() string { if node == nil { return "" } dir := "-" if node.Data.FileInfo.IsDir { dir = "d" } fm := permbits.FileMode(node.Data.FileInfo.Mode) var fileMode strings.Builder fileMode.Grow(9) cond := func(c bool, x, y byte) byte { if c { return x } else { return y } } fileMode.WriteByte(cond(fm.UserRead(), 'r', '-')) fileMode.WriteByte(cond(fm.UserWrite(), 'w', '-')) fileMode.WriteByte(cond(fm.UserExecute(), cond(fm.Setuid(), 's', 'x'), cond(fm.Setuid(), 'S', '-'))) fileMode.WriteByte(cond(fm.GroupRead(), 'r', '-')) fileMode.WriteByte(cond(fm.GroupWrite(), 'w', '-')) fileMode.WriteByte(cond(fm.GroupExecute(), cond(fm.Setgid(), 's', 'x'), cond(fm.Setgid(), 'S', '-'))) fileMode.WriteByte(cond(fm.OtherRead(), 'r', '-')) fileMode.WriteByte(cond(fm.OtherWrite(), 'w', '-')) fileMode.WriteByte(cond(fm.OtherExecute(), cond(fm.Sticky(), 't', 'x'), cond(fm.Sticky(), 'T', '-'))) user := node.Data.FileInfo.Uid group := node.Data.FileInfo.Gid userGroup := fmt.Sprintf("%d:%d", user, group) // don't include file sizes of children that have been removed (unless the node in question is a removed dir, // then show the accumulated size of removed files) sizeBytes := node.GetSize() size := humanize.Bytes(uint64(sizeBytes)) return diffTypeColor[node.Data.DiffType].Sprint(fmt.Sprintf(AttributeFormat, dir, fileMode.String(), userGroup, size)) } func (node *FileNode) GetSize() int64 { if 0 <= node.Size { return node.Size } var sizeBytes int64 if node.IsLeaf() { sizeBytes = node.Data.FileInfo.Size } else { sizer := func(curNode *FileNode) error { if curNode.Data.DiffType != Removed || node.Data.DiffType == Removed { sizeBytes += curNode.Data.FileInfo.Size } return nil } err := node.VisitDepthChildFirst(sizer, nil, nil) if err != nil { log.WithFields("error", err).Debug("unable to propagate tree to get file size") } } node.Size = sizeBytes return node.Size } // VisitDepthChildFirst iterates a tree depth-first (starting at this FileNode), evaluating the deepest depths first (visit on bubble up) func (node *FileNode) VisitDepthChildFirst(visitor Visitor, evaluator VisitEvaluator, sorter OrderStrategy) error { if sorter == nil { sorter = GetSortOrderStrategy(ByName) } keys := sorter.orderKeys(node.Children) for _, name := range keys { child := node.Children[name] err := child.VisitDepthChildFirst(visitor, evaluator, sorter) if err != nil { return err } } // never visit the root node if node == node.Tree.Root { return nil } else if evaluator != nil && evaluator(node) || evaluator == nil { return visitor(node) } return nil } // VisitDepthParentFirst iterates a tree depth-first (starting at this FileNode), evaluating the shallowest depths first (visit while sinking down) func (node *FileNode) VisitDepthParentFirst(visitor Visitor, evaluator VisitEvaluator, sorter OrderStrategy) error { var err error doVisit := evaluator != nil && evaluator(node) || evaluator == nil if !doVisit { return nil } // never visit the root node if node != node.Tree.Root { err = visitor(node) if err != nil { return err } } if sorter == nil { sorter = GetSortOrderStrategy(ByName) } keys := sorter.orderKeys(node.Children) for _, name := range keys { child := node.Children[name] err = child.VisitDepthParentFirst(visitor, evaluator, sorter) if err != nil { return err } } return err } // IsWhiteout returns an indication if this file may be a overlay-whiteout file. func (node *FileNode) IsWhiteout() bool { return strings.HasPrefix(node.Name, whiteoutPrefix) } // IsLeaf returns true is the current node has no child nodes. func (node *FileNode) IsLeaf() bool { return len(node.Children) == 0 } // Path returns a slash-delimited string from the root of the greater tree to the current node (e.g. /a/path/to/here) func (node *FileNode) Path() string { if node.path == "" { var path []string curNode := node for { if curNode.Parent == nil { break } name := curNode.Name if curNode == node { // white out prefixes are fictitious on leaf nodes name = strings.TrimPrefix(name, whiteoutPrefix) } path = append([]string{name}, path...) curNode = curNode.Parent } node.path = "/" + strings.Join(path, "/") } return strings.Replace(node.path, "//", "/", -1) } // deriveDiffType determines a DiffType to the current FileNode. Note: the DiffType of a node is always the DiffType of // its attributes and its contents. The contents are the bytes of the file of the children of a directory. func (node *FileNode) deriveDiffType(diffType DiffType) error { if node.IsLeaf() { return node.AssignDiffType(diffType) } myDiffType := diffType for _, v := range node.Children { myDiffType = myDiffType.merge(v.Data.DiffType) } return node.AssignDiffType(myDiffType) } // AssignDiffType will assign the given DiffType to this node, possibly affecting child nodes. func (node *FileNode) AssignDiffType(diffType DiffType) error { var err error node.Data.DiffType = diffType if diffType == Removed { // if we've removed this node, then all children have been removed as well for _, child := range node.Children { err = child.AssignDiffType(diffType) if err != nil { return err } } } return nil } // compare the current node against the given node, returning a definitive DiffType. func (node *FileNode) compare(other *FileNode) DiffType { if node == nil && other == nil { return Unmodified } if node == nil && other != nil { return Added } if node != nil && other == nil { return Removed } if other.IsWhiteout() { return Removed } if node.Name != other.Name { panic("comparing mismatched nodes") } return node.Data.FileInfo.Compare(other.Data.FileInfo) }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/filetree/file_tree.go
dive/filetree/file_tree.go
package filetree import ( "fmt" "github.com/wagoodman/dive/internal/log" "path" "strings" "github.com/google/uuid" ) const ( newLine = "\n" noBranchSpace = " " branchSpace = "β”‚ " middleItem = "β”œβ”€" lastItem = "└─" whiteoutPrefix = ".wh." doubleWhiteoutPrefix = ".wh..wh.." uncollapsedItem = "─ " collapsedItem = "βŠ• " ) // FileTree represents a set of files, directories, and their relations. type FileTree struct { Root *FileNode Size int FileSize uint64 Name string Id uuid.UUID SortOrder SortOrder } // NewFileTree creates an empty FileTree func NewFileTree() (tree *FileTree) { tree = new(FileTree) tree.Size = 0 tree.Root = new(FileNode) tree.Root.Tree = tree tree.Root.Children = make(map[string]*FileNode) tree.Id = uuid.New() tree.SortOrder = ByName return tree } // renderParams is a representation of a FileNode in the context of the greater tree. All // data stored is necessary for rendering a single line in a tree format. type renderParams struct { node *FileNode spaces []bool childSpaces []bool showCollapsed bool isLast bool } // renderStringTreeBetween returns a string representing the given tree between the given rows. Since each node // is rendered on its own line, the returned string shows the visible nodes not affected by a collapsed parent. func (tree *FileTree) renderStringTreeBetween(startRow, stopRow int, showAttributes bool) string { // generate a list of nodes to render var params = make([]renderParams, 0) var result string // visit from the front of the list var paramsToVisit = []renderParams{{node: tree.Root, spaces: []bool{}, showCollapsed: false, isLast: false}} for currentRow := 0; len(paramsToVisit) > 0 && currentRow <= stopRow; currentRow++ { // pop the first node var currentParams renderParams currentParams, paramsToVisit = paramsToVisit[0], paramsToVisit[1:] // take note of the next nodes to visit later sorter := GetSortOrderStrategy(tree.SortOrder) keys := sorter.orderKeys(currentParams.node.Children) var childParams = make([]renderParams, 0) for idx, name := range keys { child := currentParams.node.Children[name] // don't visit this node... if child.Data.ViewInfo.Hidden || currentParams.node.Data.ViewInfo.Collapsed { continue } // visit this node... isLast := idx == (len(currentParams.node.Children) - 1) showCollapsed := child.Data.ViewInfo.Collapsed && len(child.Children) > 0 // completely copy the reference slice childSpaces := make([]bool, len(currentParams.childSpaces)) copy(childSpaces, currentParams.childSpaces) if len(child.Children) > 0 && !child.Data.ViewInfo.Collapsed { childSpaces = append(childSpaces, isLast) } childParams = append(childParams, renderParams{ node: child, spaces: currentParams.childSpaces, childSpaces: childSpaces, showCollapsed: showCollapsed, isLast: isLast, }) } // keep the child nodes to visit later paramsToVisit = append(childParams, paramsToVisit...) // never process the root node if currentParams.node == tree.Root { currentRow-- continue } // process the current node if currentRow >= startRow && currentRow <= stopRow { params = append(params, currentParams) } } // render the result for idx := range params { currentParams := params[idx] if showAttributes { result += currentParams.node.MetadataString() + " " } result += currentParams.node.renderTreeLine(currentParams.spaces, currentParams.isLast, currentParams.showCollapsed) } return result } func (tree *FileTree) VisibleSize() int { var size int visitor := func(node *FileNode) error { size++ return nil } visitEvaluator := func(node *FileNode) bool { if node.Data.FileInfo.IsDir { // we won't visit a collapsed dir, but we need to count it if node.Data.ViewInfo.Collapsed { size++ } return !node.Data.ViewInfo.Collapsed && !node.Data.ViewInfo.Hidden } return !node.Data.ViewInfo.Hidden } err := tree.VisitDepthParentFirst(visitor, visitEvaluator) if err != nil { log.WithFields("error", err).Debug("unable to determine visible tree size") } // don't include root size-- return size } // String returns the entire tree in an ASCII representation. func (tree *FileTree) String(showAttributes bool) string { return tree.renderStringTreeBetween(0, tree.Size, showAttributes) } // StringBetween returns a partial tree in an ASCII representation. func (tree *FileTree) StringBetween(start, stop int, showAttributes bool) string { return tree.renderStringTreeBetween(start, stop, showAttributes) } // Copy returns a copy of the given FileTree func (tree *FileTree) Copy() *FileTree { newTree := NewFileTree() newTree.Size = tree.Size newTree.FileSize = tree.FileSize newTree.Root = tree.Root.Copy(newTree.Root) newTree.SortOrder = tree.SortOrder // update the tree pointers err := newTree.VisitDepthChildFirst(func(node *FileNode) error { node.Tree = newTree return nil }, nil) if err != nil { log.WithFields("error", err).Debug("unable to propagate tree on copy") } return newTree } // Visitor is a function that processes, observes, or otherwise transforms the given node type Visitor func(*FileNode) error // VisitEvaluator is a function that indicates whether the given node should be visited by a Visitor. type VisitEvaluator func(*FileNode) bool // VisitDepthChildFirst iterates the given tree depth-first, evaluating the deepest depths first (visit on bubble up) func (tree *FileTree) VisitDepthChildFirst(visitor Visitor, evaluator VisitEvaluator) error { sorter := GetSortOrderStrategy(tree.SortOrder) return tree.Root.VisitDepthChildFirst(visitor, evaluator, sorter) } // VisitDepthParentFirst iterates the given tree depth-first, evaluating the shallowest depths first (visit while sinking down) func (tree *FileTree) VisitDepthParentFirst(visitor Visitor, evaluator VisitEvaluator) error { sorter := GetSortOrderStrategy(tree.SortOrder) return tree.Root.VisitDepthParentFirst(visitor, evaluator, sorter) } // Stack takes two trees and combines them together. This is done by "stacking" the given tree on top of the owning tree. func (tree *FileTree) Stack(upper *FileTree) (failed []PathError, stackErr error) { graft := func(node *FileNode) error { if node.IsWhiteout() { err := tree.RemovePath(node.Path()) if err != nil { failed = append(failed, NewPathError(node.Path(), ActionAdd, err)) } } else { _, _, err := tree.AddPath(node.Path(), node.Data.FileInfo) if err != nil { failed = append(failed, NewPathError(node.Path(), ActionRemove, err)) } } return nil } stackErr = upper.VisitDepthChildFirst(graft, nil) return failed, stackErr } // GetNode fetches a single node when given a slash-delimited string from root ('/') to the desired node (e.g. '/a/node/path') func (tree *FileTree) GetNode(path string) (*FileNode, error) { nodeNames := strings.Split(strings.Trim(path, "/"), "/") node := tree.Root for _, name := range nodeNames { if name == "" { continue } if node.Children[name] == nil { return nil, fmt.Errorf("path does not exist: %s", path) } node = node.Children[name] } return node, nil } // AddPath adds a new node to the tree with the given payload func (tree *FileTree) AddPath(filepath string, data FileInfo) (*FileNode, []*FileNode, error) { filepath = path.Clean(filepath) if filepath == "." { return nil, nil, fmt.Errorf("cannot add relative path '%s'", filepath) } nodeNames := strings.Split(strings.Trim(filepath, "/"), "/") node := tree.Root addedNodes := make([]*FileNode, 0) for idx, name := range nodeNames { if name == "" { continue } // find or create node if node.Children[name] != nil { node = node.Children[name] } else { // don't add paths that should be deleted if strings.HasPrefix(name, doubleWhiteoutPrefix) { return nil, addedNodes, nil } // don't attach the payload. The payload is destined for the // Path's end node, not any intermediary node. node = node.AddChild(name, FileInfo{}) addedNodes = append(addedNodes, node) if node == nil { // the child could not be added return node, addedNodes, fmt.Errorf("could not add child node: '%s' (path:'%s')", name, filepath) } } // attach payload to the last specified node if idx == len(nodeNames)-1 { node.Data.FileInfo = data } } return node, addedNodes, nil } // RemovePath removes a node from the tree given its path. func (tree *FileTree) RemovePath(path string) error { node, err := tree.GetNode(path) if err != nil { return err } return node.Remove() } type compareMark struct { lowerNode *FileNode upperNode *FileNode tentative DiffType final DiffType } // CompareAndMark marks the FileNodes in the owning (lower) tree with DiffType annotations when compared to the given (upper) tree. func (tree *FileTree) CompareAndMark(upper *FileTree) ([]PathError, error) { // always compare relative to the original, unaltered tree. originalTree := tree modifications := make([]compareMark, 0) failed := make([]PathError, 0) graft := func(upperNode *FileNode) error { if upperNode.IsWhiteout() { err := tree.markRemoved(upperNode.Path()) if err != nil { failed = append(failed, NewPathError(upperNode.Path(), ActionRemove, err)) } return nil } // note: since we are not comparing against the original tree (copying the tree is expensive) we may mark the parent // of an added node incorrectly as modified. This will be corrected later. originalLowerNode, _ := originalTree.GetNode(upperNode.Path()) if originalLowerNode == nil { _, newNodes, err := tree.AddPath(upperNode.Path(), upperNode.Data.FileInfo) if err != nil { failed = append(failed, NewPathError(upperNode.Path(), ActionAdd, err)) return nil } for idx := len(newNodes) - 1; idx >= 0; idx-- { newNode := newNodes[idx] modifications = append(modifications, compareMark{lowerNode: newNode, upperNode: upperNode, tentative: -1, final: Added}) } return nil } // the file exists in the lower layer lowerNode, _ := tree.GetNode(upperNode.Path()) diffType := lowerNode.compare(upperNode) modifications = append(modifications, compareMark{lowerNode: lowerNode, upperNode: upperNode, tentative: diffType, final: -1}) return nil } // we must visit from the leaves upwards to ensure that diff types can be derived from and assigned to children err := upper.VisitDepthChildFirst(graft, nil) if err != nil { return failed, err } // take note of the comparison results on each note in the owning tree. for _, pair := range modifications { if pair.final > 0 { err = pair.lowerNode.AssignDiffType(pair.final) if err != nil { return failed, err } } else if pair.lowerNode.Data.DiffType == Unmodified { err = pair.lowerNode.deriveDiffType(pair.tentative) if err != nil { return failed, err } } // persist the upper's payload on the owning tree pair.lowerNode.Data.FileInfo = *pair.upperNode.Data.FileInfo.Copy() } return failed, nil } // markRemoved annotates the FileNode at the given path as Removed. func (tree *FileTree) markRemoved(path string) error { node, err := tree.GetNode(path) if err != nil { return err } return node.AssignDiffType(Removed) } // StackTreeRange combines an array of trees into a single tree func StackTreeRange(trees []*FileTree, start, stop int) (*FileTree, []PathError, error) { errors := make([]PathError, 0) tree := trees[0].Copy() for idx := start; idx <= stop; idx++ { failedPaths, err := tree.Stack(trees[idx]) if len(failedPaths) > 0 { errors = append(errors, failedPaths...) } if err != nil { return nil, nil, fmt.Errorf("could not stack tree range: %w", err) } } return tree, errors, nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/filetree/view_info.go
dive/filetree/view_info.go
package filetree // ViewInfo contains UI specific detail for a specific FileNode type ViewInfo struct { Collapsed bool Hidden bool } // NewViewInfo creates a default ViewInfo func NewViewInfo() (view *ViewInfo) { return &ViewInfo{ Collapsed: GlobalFileTreeCollapse, Hidden: false, } } // Copy duplicates a ViewInfo func (view *ViewInfo) Copy() (newView *ViewInfo) { newView = NewViewInfo() *newView = *view return newView }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/filetree/diff.go
dive/filetree/diff.go
package filetree import ( "fmt" ) const ( Unmodified DiffType = iota Modified Added Removed ) // DiffType defines the comparison result between two FileNodes type DiffType int // String of a DiffType func (diff DiffType) String() string { switch diff { case Unmodified: return "Unmodified" case Modified: return "Modified" case Added: return "Added" case Removed: return "Removed" default: return fmt.Sprintf("%d", int(diff)) } } // merge two DiffTypes into a single result. Essentially, return the given value unless they two values differ, // in which case we can only determine that there is "a change". func (diff DiffType) merge(other DiffType) DiffType { if diff == other { return diff } return Modified }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/filetree/order_strategy.go
dive/filetree/order_strategy.go
package filetree import ( "sort" ) type SortOrder int const ( ByName = iota BySizeDesc NumSortOrderConventions ) type OrderStrategy interface { orderKeys(files map[string]*FileNode) []string } func GetSortOrderStrategy(sortOrder SortOrder) OrderStrategy { switch sortOrder { case ByName: return orderByNameStrategy{} case BySizeDesc: return orderBySizeDescStrategy{} } return orderByNameStrategy{} } type orderByNameStrategy struct{} func (orderByNameStrategy) orderKeys(files map[string]*FileNode) []string { var keys []string for key := range files { keys = append(keys, key) } sort.Strings(keys) return keys } type orderBySizeDescStrategy struct{} func (orderBySizeDescStrategy) orderKeys(files map[string]*FileNode) []string { var keys []string for key := range files { keys = append(keys, key) } sort.Slice(keys, func(i, j int) bool { ki, kj := keys[i], keys[j] ni, nj := files[ki], files[kj] if ni.GetSize() == nj.GetSize() { return ki < kj } return ni.GetSize() > nj.GetSize() }) return keys }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/filetree/efficiency_test.go
dive/filetree/efficiency_test.go
package filetree import ( "testing" ) func checkError(t *testing.T, err error, message string) { if err != nil { t.Errorf(message+": %+v", err) } } func TestEfficiency(t *testing.T) { trees := make([]*FileTree, 3) for idx := range trees { trees[idx] = NewFileTree() } _, _, err := trees[0].AddPath("/etc/nginx/nginx.conf", FileInfo{Size: 2000}) checkError(t, err, "could not setup test") _, _, err = trees[0].AddPath("/etc/nginx/public", FileInfo{Size: 3000}) checkError(t, err, "could not setup test") _, _, err = trees[1].AddPath("/etc/nginx/nginx.conf", FileInfo{Size: 5000}) checkError(t, err, "could not setup test") _, _, err = trees[1].AddPath("/etc/athing", FileInfo{Size: 10000}) checkError(t, err, "could not setup test") _, _, err = trees[2].AddPath("/etc/.wh.nginx", *BlankFileChangeInfo("/etc/.wh.nginx")) checkError(t, err, "could not setup test") var expectedScore = 0.75 var expectedMatches = EfficiencySlice{ &EfficiencyData{Path: "/etc/nginx/nginx.conf", CumulativeSize: 7000}, } actualScore, actualMatches := Efficiency(trees) if expectedScore != actualScore { t.Errorf("Expected score of %v but go %v", expectedScore, actualScore) } if len(actualMatches) != len(expectedMatches) { for _, match := range actualMatches { t.Logf(" match: %+v", match) } t.Fatalf("Expected to find %d inefficient paths, but found %d", len(expectedMatches), len(actualMatches)) } if expectedMatches[0].Path != actualMatches[0].Path { t.Errorf("Expected path of %s but go %s", expectedMatches[0].Path, actualMatches[0].Path) } if expectedMatches[0].CumulativeSize != actualMatches[0].CumulativeSize { t.Errorf("Expected cumulative size of %v but go %v", expectedMatches[0].CumulativeSize, actualMatches[0].CumulativeSize) } } func TestEfficiency_ScratchImage(t *testing.T) { trees := make([]*FileTree, 3) for idx := range trees { trees[idx] = NewFileTree() } _, _, err := trees[0].AddPath("/nothing", FileInfo{Size: 0}) checkError(t, err, "could not setup test") var expectedScore = 1.0 var expectedMatches = EfficiencySlice{} actualScore, actualMatches := Efficiency(trees) if expectedScore != actualScore { t.Errorf("Expected score of %v but go %v", expectedScore, actualScore) } if len(actualMatches) > 0 { t.Fatalf("Expected to find %d inefficient paths, but found %d", len(expectedMatches), len(actualMatches)) } }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/filetree/comparer.go
dive/filetree/comparer.go
package filetree import ( "fmt" ) type TreeIndexKey struct { bottomTreeStart, bottomTreeStop, topTreeStart, topTreeStop int } func NewTreeIndexKey(bottomTreeStart, bottomTreeStop, topTreeStart, topTreeStop int) TreeIndexKey { return TreeIndexKey{ bottomTreeStart: bottomTreeStart, bottomTreeStop: bottomTreeStop, topTreeStart: topTreeStart, topTreeStop: topTreeStop, } } func (index TreeIndexKey) String() string { if index.bottomTreeStart == index.bottomTreeStop && index.topTreeStart == index.topTreeStop { return fmt.Sprintf("Index(%d:%d)", index.bottomTreeStart, index.topTreeStart) } else if index.bottomTreeStart == index.bottomTreeStop { return fmt.Sprintf("Index(%d:%d-%d)", index.bottomTreeStart, index.topTreeStart, index.topTreeStop) } else if index.topTreeStart == index.topTreeStop { return fmt.Sprintf("Index(%d-%d:%d)", index.bottomTreeStart, index.bottomTreeStop, index.topTreeStart) } return fmt.Sprintf("Index(%d-%d:%d-%d)", index.bottomTreeStart, index.bottomTreeStop, index.topTreeStart, index.topTreeStop) } type Comparer struct { refTrees []*FileTree trees map[TreeIndexKey]*FileTree pathErrors map[TreeIndexKey][]PathError } func NewComparer(refTrees []*FileTree) Comparer { return Comparer{ refTrees: refTrees, trees: make(map[TreeIndexKey]*FileTree), pathErrors: make(map[TreeIndexKey][]PathError), } } func (cmp *Comparer) GetPathErrors(key TreeIndexKey) ([]PathError, error) { _, pathErrors, err := cmp.get(key) if err != nil { return nil, err } return pathErrors, nil } func (cmp *Comparer) GetTree(key TreeIndexKey) (*FileTree, error) { // func (cmp *Comparer) GetTree(bottomTreeStart, bottomTreeStop, topTreeStart, topTreeStop int) (*FileTree, []PathError, error) { // key := TreeIndexKey{bottomTreeStart, bottomTreeStop, topTreeStart, topTreeStop} if value, exists := cmp.trees[key]; exists { return value, nil } value, pathErrors, err := cmp.get(key) if err != nil { return nil, err } cmp.trees[key] = value cmp.pathErrors[key] = pathErrors return value, nil } func (cmp *Comparer) get(key TreeIndexKey) (*FileTree, []PathError, error) { newTree, pathErrors, err := StackTreeRange(cmp.refTrees, key.bottomTreeStart, key.bottomTreeStop) if err != nil { return nil, nil, err } for idx := key.topTreeStart; idx <= key.topTreeStop; idx++ { markPathErrors, err := newTree.CompareAndMark(cmp.refTrees[idx]) pathErrors = append(pathErrors, markPathErrors...) if err != nil { return nil, nil, fmt.Errorf("failed to build tree: %w", err) } } return newTree, pathErrors, nil } // case 1: layer compare (top tree SIZE is fixed (BUT floats forward), Bottom tree SIZE changes) func (cmp *Comparer) NaturalIndexes() <-chan TreeIndexKey { indexes := make(chan TreeIndexKey) go func() { defer close(indexes) var bottomTreeStart, bottomTreeStop, topTreeStart, topTreeStop int for selectIdx := 0; selectIdx < len(cmp.refTrees); selectIdx++ { bottomTreeStart = 0 topTreeStop = selectIdx if selectIdx == 0 { bottomTreeStop = selectIdx topTreeStart = selectIdx } else { bottomTreeStop = selectIdx - 1 topTreeStart = selectIdx } indexes <- TreeIndexKey{ bottomTreeStart: bottomTreeStart, bottomTreeStop: bottomTreeStop, topTreeStart: topTreeStart, topTreeStop: topTreeStop, } } }() return indexes } // case 2: aggregated compare (bottom tree is ENTIRELY fixed, top tree SIZE changes) func (cmp *Comparer) AggregatedIndexes() <-chan TreeIndexKey { indexes := make(chan TreeIndexKey) go func() { defer close(indexes) var bottomTreeStart, bottomTreeStop, topTreeStart, topTreeStop int for selectIdx := 0; selectIdx < len(cmp.refTrees); selectIdx++ { bottomTreeStart = 0 topTreeStop = selectIdx if selectIdx == 0 { bottomTreeStop = selectIdx topTreeStart = selectIdx } else { bottomTreeStop = 0 topTreeStart = 1 } indexes <- TreeIndexKey{ bottomTreeStart: bottomTreeStart, bottomTreeStop: bottomTreeStop, topTreeStart: topTreeStart, topTreeStop: topTreeStop, } } }() return indexes } func (cmp *Comparer) BuildCache() (errors []error) { for index := range cmp.NaturalIndexes() { pathError, _ := cmp.GetPathErrors(index) if len(pathError) > 0 { for _, path := range pathError { errors = append(errors, fmt.Errorf("path error at layer index %s: %s", index, path)) } } _, err := cmp.GetTree(index) if err != nil { errors = append(errors, err) return errors } } for index := range cmp.AggregatedIndexes() { _, err := cmp.GetTree(index) if err != nil { errors = append(errors, err) return errors } } return errors }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/filetree/path_error.go
dive/filetree/path_error.go
package filetree import "fmt" const ( ActionAdd FileAction = iota ActionRemove ) type FileAction int func (fa FileAction) String() string { switch fa { case ActionAdd: return "add" case ActionRemove: return "remove" default: return "<unknown file action>" } } type PathError struct { Path string Action FileAction Err error } func NewPathError(path string, action FileAction, err error) PathError { return PathError{ Path: path, Action: action, Err: err, } } func (pe PathError) String() string { return fmt.Sprintf("unable to %s '%s': %+v", pe.Action.String(), pe.Path, pe.Err) }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/filetree/efficiency.go
dive/filetree/efficiency.go
package filetree import ( "fmt" "github.com/wagoodman/dive/internal/log" "sort" ) // EfficiencyData represents the storage and reference statistics for a given file tree path. type EfficiencyData struct { Path string Nodes []*FileNode CumulativeSize int64 minDiscoveredSize int64 } // EfficiencySlice represents an ordered set of EfficiencyData data structures. type EfficiencySlice []*EfficiencyData // Len is required for sorting. func (efs EfficiencySlice) Len() int { return len(efs) } // Swap operation is required for sorting. func (efs EfficiencySlice) Swap(i, j int) { efs[i], efs[j] = efs[j], efs[i] } // Less comparison is required for sorting. func (efs EfficiencySlice) Less(i, j int) bool { return efs[i].CumulativeSize < efs[j].CumulativeSize } // Efficiency returns the score and file set of the given set of FileTrees (layers). This is loosely based on: // 1. Files that are duplicated across layers discounts your score, weighted by file size // 2. Files that are removed discounts your score, weighted by the original file size func Efficiency(trees []*FileTree) (float64, EfficiencySlice) { efficiencyMap := make(map[string]*EfficiencyData) inefficientMatches := make(EfficiencySlice, 0) currentTree := 0 visitor := func(node *FileNode) error { path := node.Path() if _, ok := efficiencyMap[path]; !ok { efficiencyMap[path] = &EfficiencyData{ Path: path, Nodes: make([]*FileNode, 0), minDiscoveredSize: -1, } } data := efficiencyMap[path] // this node may have had children that were deleted, however, we won't explicitly list out every child, only // the top-most parent with the cumulative size. These operations will need to be done on the full (stacked) // tree. // Note: whiteout files may also represent directories, so we need to find out if this was previously a file or dir. var sizeBytes int64 if node.IsWhiteout() { sizer := func(curNode *FileNode) error { sizeBytes += curNode.Data.FileInfo.Size return nil } stackedTree, failedPaths, err := StackTreeRange(trees, 0, currentTree-1) if len(failedPaths) > 0 { for _, path := range failedPaths { log.WithFields("path", path.String()).Debug("unable to include path in stacked tree") } } if err != nil { return fmt.Errorf("unable to stack tree range: %w", err) } previousTreeNode, err := stackedTree.GetNode(node.Path()) if err != nil { return err } if previousTreeNode.Data.FileInfo.IsDir { err = previousTreeNode.VisitDepthChildFirst(sizer, nil, nil) if err != nil { return fmt.Errorf("unable to propagate whiteout dir: %w", err) } } } else { sizeBytes = node.Data.FileInfo.Size } data.CumulativeSize += sizeBytes if data.minDiscoveredSize < 0 || sizeBytes < data.minDiscoveredSize { data.minDiscoveredSize = sizeBytes } data.Nodes = append(data.Nodes, node) if len(data.Nodes) == 2 { inefficientMatches = append(inefficientMatches, data) } return nil } visitEvaluator := func(node *FileNode) bool { return node.IsLeaf() } for idx, tree := range trees { currentTree = idx err := tree.VisitDepthChildFirst(visitor, visitEvaluator) if err != nil { log.WithFields("layer", tree.Id, "error", err).Debug("unable to propagate layer tree") } } // calculate the score var minimumPathSizes int64 var discoveredPathSizes int64 for _, value := range efficiencyMap { minimumPathSizes += value.minDiscoveredSize discoveredPathSizes += value.CumulativeSize } var score float64 if discoveredPathSizes == 0 { score = 1.0 } else { score = float64(minimumPathSizes) / float64(discoveredPathSizes) } sort.Sort(inefficientMatches) return score, inefficientMatches }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/filetree/file_node_test.go
dive/filetree/file_node_test.go
package filetree import ( "testing" ) func TestAddChild(t *testing.T) { var expected, actual int tree := NewFileTree() payload := FileInfo{ Path: "stufffffs", } one := tree.Root.AddChild("first node!", payload) two := tree.Root.AddChild("nil node!", FileInfo{}) tree.Root.AddChild("third node!", FileInfo{}) two.AddChild("forth, one level down...", FileInfo{}) two.AddChild("fifth, one level down...", FileInfo{}) two.AddChild("fifth, one level down...", FileInfo{}) expected, actual = 5, tree.Size if expected != actual { t.Errorf("Expected a tree size of %d got %d.", expected, actual) } expected, actual = 2, len(two.Children) if expected != actual { t.Errorf("Expected 'twos' number of children to be %d got %d.", expected, actual) } expected, actual = 3, len(tree.Root.Children) if expected != actual { t.Errorf("Expected 'twos' number of children to be %d got %d.", expected, actual) } expectedFC := FileInfo{ Path: "stufffffs", } actualFC := one.Data.FileInfo if expectedFC.Path != actualFC.Path { t.Errorf("Expected 'ones' payload to be %+v got %+v.", expectedFC, actualFC) } } func TestRemoveChild(t *testing.T) { var expected, actual int tree := NewFileTree() tree.Root.AddChild("first", FileInfo{}) two := tree.Root.AddChild("nil", FileInfo{}) tree.Root.AddChild("third", FileInfo{}) forth := two.AddChild("forth", FileInfo{}) two.AddChild("fifth", FileInfo{}) err := forth.Remove() checkError(t, err, "unable to setup test") expected, actual = 4, tree.Size if expected != actual { t.Errorf("Expected a tree size of %d got %d.", expected, actual) } if tree.Root.Children["forth"] != nil { t.Errorf("Expected 'forth' node to be deleted.") } err = two.Remove() checkError(t, err, "unable to setup test") expected, actual = 2, tree.Size if expected != actual { t.Errorf("Expected a tree size of %d got %d.", expected, actual) } if tree.Root.Children["nil"] != nil { t.Errorf("Expected 'nil' node to be deleted.") } } func TestPath(t *testing.T) { expected := "/etc/nginx/nginx.conf" tree := NewFileTree() node, _, _ := tree.AddPath(expected, FileInfo{}) actual := node.Path() if expected != actual { t.Errorf("Expected path '%s' got '%s'", expected, actual) } } func TestIsWhiteout(t *testing.T) { tree1 := NewFileTree() p1, _, _ := tree1.AddPath("/etc/nginx/public1", FileInfo{}) p2, _, _ := tree1.AddPath("/etc/nginx/.wh.public2", FileInfo{}) p3, _, _ := tree1.AddPath("/etc/nginx/public3/.wh..wh..opq", FileInfo{}) if p1.IsWhiteout() != false { t.Errorf("Expected path '%s' to **not** be a whiteout file", p1.Name) } if p2.IsWhiteout() != true { t.Errorf("Expected path '%s' to be a whiteout file", p2.Name) } if p3 != nil { t.Errorf("Expected to not be able to add path '%s'", p2.Name) } } func TestDiffTypeFromAddedChildren(t *testing.T) { tree := NewFileTree() node, _, _ := tree.AddPath("/usr", *BlankFileChangeInfo("/usr")) node.Data.DiffType = Unmodified node, _, _ = tree.AddPath("/usr/bin", *BlankFileChangeInfo("/usr/bin")) node.Data.DiffType = Added node, _, _ = tree.AddPath("/usr/bin2", *BlankFileChangeInfo("/usr/bin2")) node.Data.DiffType = Removed err := tree.Root.Children["usr"].deriveDiffType(Unmodified) checkError(t, err, "unable to setup test") if tree.Root.Children["usr"].Data.DiffType != Modified { t.Errorf("Expected Modified but got %v", tree.Root.Children["usr"].Data.DiffType) } } func TestDiffTypeFromRemovedChildren(t *testing.T) { tree := NewFileTree() _, _, _ = tree.AddPath("/usr", *BlankFileChangeInfo("/usr")) info1 := BlankFileChangeInfo("/usr/.wh.bin") node, _, _ := tree.AddPath("/usr/.wh.bin", *info1) node.Data.DiffType = Removed info2 := BlankFileChangeInfo("/usr/.wh.bin2") node, _, _ = tree.AddPath("/usr/.wh.bin2", *info2) node.Data.DiffType = Removed err := tree.Root.Children["usr"].deriveDiffType(Unmodified) checkError(t, err, "unable to setup test") if tree.Root.Children["usr"].Data.DiffType != Modified { t.Errorf("Expected Modified but got %v", tree.Root.Children["usr"].Data.DiffType) } } func TestDirSize(t *testing.T) { tree1 := NewFileTree() _, _, err := tree1.AddPath("/etc/nginx/public1", FileInfo{Size: 100}) checkError(t, err, "unable to setup test") _, _, err = tree1.AddPath("/etc/nginx/thing1", FileInfo{Size: 200}) checkError(t, err, "unable to setup test") _, _, err = tree1.AddPath("/etc/nginx/public3/thing2", FileInfo{Size: 300}) checkError(t, err, "unable to setup test") node, _ := tree1.GetNode("/etc/nginx") expected, actual := "---------- 0:0 600 B ", node.MetadataString() if expected != actual { t.Errorf("Expected metadata '%s' got '%s'", expected, actual) } }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/internal/utils/view.go
internal/utils/view.go
package utils import ( "errors" "github.com/awesome-gocui/gocui" "github.com/wagoodman/dive/internal/log" ) // IsNewView determines if a view has already been created based on the set of errors given (a bit hokie) func IsNewView(errs ...error) bool { for _, err := range errs { if err == nil { return false } if !errors.Is(err, gocui.ErrUnknownView) { log.WithFields("error", err).Error("IsNewView() unexpected error") return true } } return true }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/internal/utils/format.go
internal/utils/format.go
package utils import ( "strings" ) // CleanArgs trims the whitespace from the given set of strings. func CleanArgs(s []string) []string { var r []string for _, str := range s { if str != "" { r = append(r, strings.Trim(str, " ")) } } return r }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/internal/bus/bus.go
internal/bus/bus.go
package bus import "github.com/wagoodman/go-partybus" var publisher partybus.Publisher func Set(p partybus.Publisher) { publisher = p } func Get() partybus.Publisher { return publisher } func Publish(e partybus.Event) { if publisher != nil { publisher.Publish(e) } }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/internal/bus/helpers.go
internal/bus/helpers.go
package bus import ( "github.com/wagoodman/dive/dive/image" "github.com/wagoodman/dive/internal/bus/event" "github.com/wagoodman/dive/internal/bus/event/payload" "github.com/wagoodman/go-partybus" "github.com/wagoodman/go-progress" ) func Report(report string) { if len(report) == 0 { return } Publish(partybus.Event{ Type: event.Report, Value: report, }) } func Notify(message string) { Publish(partybus.Event{ Type: event.Notification, Value: message, }) } func StartTask(info payload.GenericTask) *payload.GenericProgress { t := &payload.GenericProgress{ AtomicStage: progress.NewAtomicStage(""), Manual: progress.NewManual(-1), } Publish(partybus.Event{ Type: event.TaskStarted, Source: info, Value: progress.StagedProgressable(t), }) return t } func StartSizedTask(info payload.GenericTask, size int64, initialStage string) *payload.GenericProgress { t := &payload.GenericProgress{ AtomicStage: progress.NewAtomicStage(initialStage), Manual: progress.NewManual(size), } Publish(partybus.Event{ Type: event.TaskStarted, Source: info, Value: progress.StagedProgressable(t), }) return t } func ExploreAnalysis(analysis image.Analysis, reader image.ContentReader) { Publish(partybus.Event{ Type: event.ExploreAnalysis, Value: payload.Explore{Analysis: analysis, Content: reader}, }) }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/internal/bus/event/event.go
internal/bus/event/event.go
package event import ( "github.com/wagoodman/go-partybus" ) const ( typePrefix = "dive-cli" // TaskStarted encompasses all events that are related to the analysis of a docker image (build, fetch, analyze) TaskStarted partybus.EventType = typePrefix + "-task-started" // ExploreAnalysis is a partybus event that occurs when an analysis result is ready for presentation to stdout ExploreAnalysis partybus.EventType = typePrefix + "-analysis" // Report is a partybus event that occurs when an analysis result is ready for final presentation to stdout Report partybus.EventType = typePrefix + "-report" // Notification is a partybus event that occurs when auxiliary information is ready for presentation to stderr Notification partybus.EventType = typePrefix + "-notification" )
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/internal/bus/event/payload/generic.go
internal/bus/event/payload/generic.go
package payload import ( "context" "github.com/wagoodman/go-progress" ) type genericProgressKey struct{} func SetGenericProgressToContext(ctx context.Context, mon *GenericProgress) context.Context { return context.WithValue(ctx, genericProgressKey{}, mon) } func GetGenericProgressFromContext(ctx context.Context) *GenericProgress { mon, ok := ctx.Value(genericProgressKey{}).(*GenericProgress) if !ok { return nil } return mon } type GenericTask struct { // required fields Title Title // optional format fields HideOnSuccess bool HideStageOnSuccess bool // optional fields ID string ParentID string Context string } type GenericProgress struct { *progress.AtomicStage *progress.Manual } type Title struct { Default string WhileRunning string OnSuccess string }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/internal/bus/event/payload/explore.go
internal/bus/event/payload/explore.go
package payload import "github.com/wagoodman/dive/dive/image" type Explore struct { Analysis image.Analysis Content image.ContentReader }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/internal/bus/event/parser/parsers.go
internal/bus/event/parser/parsers.go
package parser import ( "fmt" "github.com/wagoodman/dive/dive/image" "github.com/wagoodman/dive/internal/bus/event" "github.com/wagoodman/dive/internal/bus/event/payload" "github.com/wagoodman/go-partybus" "github.com/wagoodman/go-progress" ) type ErrBadPayload struct { Type partybus.EventType Field string Value interface{} } func (e *ErrBadPayload) Error() string { return fmt.Sprintf("event='%s' has bad event payload field=%q: %q", string(e.Type), e.Field, e.Value) } func newPayloadErr(t partybus.EventType, field string, value interface{}) error { return &ErrBadPayload{ Type: t, Field: field, Value: value, } } func checkEventType(actual, expected partybus.EventType) error { if actual != expected { return newPayloadErr(expected, "Type", actual) } return nil } func ParseTaskStarted(e partybus.Event) (progress.StagedProgressable, *payload.GenericTask, error) { if err := checkEventType(e.Type, event.TaskStarted); err != nil { return nil, nil, err } var mon progress.StagedProgressable source, ok := e.Source.(payload.GenericTask) if !ok { return nil, nil, newPayloadErr(e.Type, "Source", e.Source) } mon, ok = e.Value.(progress.StagedProgressable) if !ok { mon = nil } return mon, &source, nil } func ParseExploreAnalysis(e partybus.Event) (image.Analysis, image.ContentReader, error) { if err := checkEventType(e.Type, event.ExploreAnalysis); err != nil { return image.Analysis{}, nil, err } ex, ok := e.Value.(payload.Explore) if !ok { return image.Analysis{}, nil, newPayloadErr(e.Type, "Value", e.Value) } return ex.Analysis, ex.Content, nil } func ParseReport(e partybus.Event) (string, string, error) { if err := checkEventType(e.Type, event.Report); err != nil { return "", "", err } context, ok := e.Source.(string) if !ok { // this is optional context = "" } report, ok := e.Value.(string) if !ok { return "", "", newPayloadErr(e.Type, "Value", e.Value) } return context, report, nil } func ParseNotification(e partybus.Event) (string, string, error) { if err := checkEventType(e.Type, event.Notification); err != nil { return "", "", err } context, ok := e.Source.(string) if !ok { // this is optional context = "" } notification, ok := e.Value.(string) if !ok { return "", "", newPayloadErr(e.Type, "Value", e.Value) } return context, notification, nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/internal/log/log.go
internal/log/log.go
package log import ( "github.com/anchore/go-logger" "github.com/anchore/go-logger/adapter/discard" ) // log is the singleton used to facilitate logging internally within var log = discard.New() // Set replaces the default logger with the provided logger. func Set(l logger.Logger) { log = l } // Get returns the current logger instance. func Get() logger.Logger { return log } // Errorf takes a formatted template string and template arguments for the error logging level. func Errorf(format string, args ...interface{}) { log.Errorf(format, args...) } // Error logs the given arguments at the error logging level. func Error(args ...interface{}) { log.Error(args...) } // Warnf takes a formatted template string and template arguments for the warning logging level. func Warnf(format string, args ...interface{}) { log.Warnf(format, args...) } // Warn logs the given arguments at the warning logging level. func Warn(args ...interface{}) { log.Warn(args...) } // Infof takes a formatted template string and template arguments for the info logging level. func Infof(format string, args ...interface{}) { log.Infof(format, args...) } // Info logs the given arguments at the info logging level. func Info(args ...interface{}) { log.Info(args...) } // Debugf takes a formatted template string and template arguments for the debug logging level. func Debugf(format string, args ...interface{}) { log.Debugf(format, args...) } // Debug logs the given arguments at the debug logging level. func Debug(args ...interface{}) { log.Debug(args...) } // Tracef takes a formatted template string and template arguments for the trace logging level. func Tracef(format string, args ...interface{}) { log.Tracef(format, args...) } // Trace logs the given arguments at the trace logging level. func Trace(args ...interface{}) { log.Trace(args...) } // WithFields returns a message logger with multiple key-value fields. func WithFields(fields ...interface{}) logger.MessageLogger { return log.WithFields(fields...) } // Nested returns a new logger with hard coded key-value pairs func Nested(fields ...interface{}) logger.Logger { return log.Nested(fields...) }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/gin_test.go
gin_test.go
// 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 gin import ( "crypto/tls" "fmt" "html/template" "io" "net" "net/http" "net/http/httptest" "reflect" "strconv" "strings" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/net/http2" ) func formatAsDate(t time.Time) string { year, month, day := t.Date() return fmt.Sprintf("%d/%02d/%02d", year, month, day) } func setupHTMLFiles(t *testing.T, mode string, tls bool, loadMethod func(*Engine)) *httptest.Server { SetMode(mode) defer SetMode(TestMode) var router *Engine captureOutput(t, func() { router = New() router.Delims("{[{", "}]}") router.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.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC), //nolint:gofumpt }) }) }) var ts *httptest.Server if tls { ts = httptest.NewTLSServer(router) } else { ts = httptest.NewServer(router) } return ts } func TestLoadHTMLGlobDebugMode(t *testing.T) { ts := setupHTMLFiles( t, DebugMode, false, func(router *Engine) { router.LoadHTMLGlob("./testdata/template/*") }, ) defer ts.Close() res, err := http.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(err) } r := Default() r.UseH2C = true r.GET("/", func(c *Context) { c.String(200, "<h1>Hello world</h1>") }) go func() { err := http.Serve(ln, r.Handler()) if err != nil { t.Log(err) } }() defer ln.Close() url := "http://" + ln.Addr().String() + "/" httpClient := http.Client{ Transport: &http2.Transport{ AllowHTTP: true, DialTLS: func(netw, addr string, cfg *tls.Config) (net.Conn, error) { return net.Dial(netw, addr) }, }, } res, err := httpClient.Get(url) if err != nil { t.Error(err) } resp, _ := io.ReadAll(res.Body) assert.Equal(t, "<h1>Hello world</h1>", string(resp)) } func TestLoadHTMLGlobTestMode(t *testing.T) { ts := setupHTMLFiles( t, TestMode, false, func(router *Engine) { router.LoadHTMLGlob("./testdata/template/*") }, ) defer ts.Close() res, err := http.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 TestLoadHTMLGlobReleaseMode(t *testing.T) { ts := setupHTMLFiles( t, ReleaseMode, false, func(router *Engine) { router.LoadHTMLGlob("./testdata/template/*") }, ) defer ts.Close() res, err := http.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 TestLoadHTMLGlobUsingTLS(t *testing.T) { ts := setupHTMLFiles( t, DebugMode, true, func(router *Engine) { router.LoadHTMLGlob("./testdata/template/*") }, ) defer ts.Close() // Use InsecureSkipVerify for avoiding `x509: certificate signed by unknown authority` error tr := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, }, } client := &http.Client{Transport: tr} res, err := client.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 TestLoadHTMLGlobFromFuncMap(t *testing.T) { ts := setupHTMLFiles( t, DebugMode, false, func(router *Engine) { router.LoadHTMLGlob("./testdata/template/*") }, ) defer ts.Close() res, err := http.Get(ts.URL + "/raw") if err != nil { t.Error(err) } resp, _ := io.ReadAll(res.Body) assert.Equal(t, "Date: 2017/07/01", string(resp)) } func init() { SetMode(TestMode) } func TestCreateEngine(t *testing.T) { router := New() assert.Equal(t, "/", router.basePath) assert.Equal(t, router.engine, router) assert.Empty(t, router.Handlers) } func TestLoadHTMLFilesTestMode(t *testing.T) { ts := setupHTMLFiles( t, TestMode, false, func(router *Engine) { router.LoadHTMLFiles("./testdata/template/hello.tmpl", "./testdata/template/raw.tmpl") }, ) defer ts.Close() res, err := http.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 TestLoadHTMLFilesDebugMode(t *testing.T) { ts := setupHTMLFiles( t, DebugMode, false, func(router *Engine) { router.LoadHTMLFiles("./testdata/template/hello.tmpl", "./testdata/template/raw.tmpl") }, ) defer ts.Close() res, err := http.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 TestLoadHTMLFilesReleaseMode(t *testing.T) { ts := setupHTMLFiles( t, ReleaseMode, false, func(router *Engine) { router.LoadHTMLFiles("./testdata/template/hello.tmpl", "./testdata/template/raw.tmpl") }, ) defer ts.Close() res, err := http.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 TestLoadHTMLFilesUsingTLS(t *testing.T) { ts := setupHTMLFiles( t, TestMode, true, func(router *Engine) { router.LoadHTMLFiles("./testdata/template/hello.tmpl", "./testdata/template/raw.tmpl") }, ) defer ts.Close() // Use InsecureSkipVerify for avoiding `x509: certificate signed by unknown authority` error tr := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, }, } client := &http.Client{Transport: tr} res, err := client.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 TestLoadHTMLFilesFuncMap(t *testing.T) { ts := setupHTMLFiles( t, TestMode, false, func(router *Engine) { router.LoadHTMLFiles("./testdata/template/hello.tmpl", "./testdata/template/raw.tmpl") }, ) defer ts.Close() res, err := http.Get(ts.URL + "/raw") if err != nil { t.Error(err) } resp, _ := io.ReadAll(res.Body) assert.Equal(t, "Date: 2017/07/01", string(resp)) } var tmplFS = http.Dir("testdata/template") func TestLoadHTMLFSTestMode(t *testing.T) { ts := setupHTMLFiles( t, TestMode, false, func(router *Engine) { router.LoadHTMLFS(tmplFS, "hello.tmpl", "raw.tmpl") }, ) defer ts.Close() res, err := http.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 TestLoadHTMLFSDebugMode(t *testing.T) { ts := setupHTMLFiles( t, DebugMode, false, func(router *Engine) { router.LoadHTMLFS(tmplFS, "hello.tmpl", "raw.tmpl") }, ) defer ts.Close() res, err := http.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 TestLoadHTMLFSReleaseMode(t *testing.T) { ts := setupHTMLFiles( t, ReleaseMode, false, func(router *Engine) { router.LoadHTMLFS(tmplFS, "hello.tmpl", "raw.tmpl") }, ) defer ts.Close() res, err := http.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 TestLoadHTMLFSUsingTLS(t *testing.T) { ts := setupHTMLFiles( t, TestMode, true, func(router *Engine) { router.LoadHTMLFS(tmplFS, "hello.tmpl", "raw.tmpl") }, ) defer ts.Close() // Use InsecureSkipVerify for avoiding `x509: certificate signed by unknown authority` error tr := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, }, } client := &http.Client{Transport: tr} res, err := client.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 TestLoadHTMLFSFuncMap(t *testing.T) { ts := setupHTMLFiles( t, TestMode, false, func(router *Engine) { router.LoadHTMLFS(tmplFS, "hello.tmpl", "raw.tmpl") }, ) defer ts.Close() res, err := http.Get(ts.URL + "/raw") if err != nil { t.Error(err) } resp, _ := io.ReadAll(res.Body) assert.Equal(t, "Date: 2017/07/01", string(resp)) } func TestAddRoute(t *testing.T) { router := New() router.addRoute(http.MethodGet, "/", HandlersChain{func(_ *Context) {}}) assert.Len(t, router.trees, 1) assert.NotNil(t, router.trees.get(http.MethodGet)) assert.Nil(t, router.trees.get(http.MethodPost)) router.addRoute(http.MethodPost, "/", HandlersChain{func(_ *Context) {}}) assert.Len(t, router.trees, 2) assert.NotNil(t, router.trees.get(http.MethodGet)) assert.NotNil(t, router.trees.get(http.MethodPost)) router.addRoute(http.MethodPost, "/post", HandlersChain{func(_ *Context) {}}) assert.Len(t, router.trees, 2) } func TestAddRouteFails(t *testing.T) { router := New() assert.Panics(t, func() { router.addRoute("", "/", HandlersChain{func(_ *Context) {}}) }) assert.Panics(t, func() { router.addRoute(http.MethodGet, "a", HandlersChain{func(_ *Context) {}}) }) assert.Panics(t, func() { router.addRoute(http.MethodGet, "/", HandlersChain{}) }) router.addRoute(http.MethodPost, "/post", HandlersChain{func(_ *Context) {}}) assert.Panics(t, func() { router.addRoute(http.MethodPost, "/post", HandlersChain{func(_ *Context) {}}) }) } func TestCreateDefaultRouter(t *testing.T) { router := Default() assert.Len(t, router.Handlers, 2) } func TestNoRouteWithoutGlobalHandlers(t *testing.T) { var middleware0 HandlerFunc = func(c *Context) {} var middleware1 HandlerFunc = func(c *Context) {} router := New() router.NoRoute(middleware0) assert.Nil(t, router.Handlers) assert.Len(t, router.noRoute, 1) assert.Len(t, router.allNoRoute, 1) compareFunc(t, router.noRoute[0], middleware0) compareFunc(t, router.allNoRoute[0], middleware0) router.NoRoute(middleware1, middleware0) assert.Len(t, router.noRoute, 2) assert.Len(t, router.allNoRoute, 2) compareFunc(t, router.noRoute[0], middleware1) compareFunc(t, router.allNoRoute[0], middleware1) compareFunc(t, router.noRoute[1], middleware0) compareFunc(t, router.allNoRoute[1], middleware0) } func TestNoRouteWithGlobalHandlers(t *testing.T) { var middleware0 HandlerFunc = func(c *Context) {} var middleware1 HandlerFunc = func(c *Context) {} var middleware2 HandlerFunc = func(c *Context) {} router := New() router.Use(middleware2) router.NoRoute(middleware0) assert.Len(t, router.allNoRoute, 2) assert.Len(t, router.Handlers, 1) assert.Len(t, router.noRoute, 1) compareFunc(t, router.Handlers[0], middleware2) compareFunc(t, router.noRoute[0], middleware0) compareFunc(t, router.allNoRoute[0], middleware2) compareFunc(t, router.allNoRoute[1], middleware0) router.Use(middleware1) assert.Len(t, router.allNoRoute, 3) assert.Len(t, router.Handlers, 2) assert.Len(t, router.noRoute, 1) compareFunc(t, router.Handlers[0], middleware2) compareFunc(t, router.Handlers[1], middleware1) compareFunc(t, router.noRoute[0], middleware0) compareFunc(t, router.allNoRoute[0], middleware2) compareFunc(t, router.allNoRoute[1], middleware1) compareFunc(t, router.allNoRoute[2], middleware0) } func TestNoMethodWithoutGlobalHandlers(t *testing.T) { var middleware0 HandlerFunc = func(c *Context) {} var middleware1 HandlerFunc = func(c *Context) {} router := New() router.NoMethod(middleware0) assert.Empty(t, router.Handlers) assert.Len(t, router.noMethod, 1) assert.Len(t, router.allNoMethod, 1) compareFunc(t, router.noMethod[0], middleware0) compareFunc(t, router.allNoMethod[0], middleware0) router.NoMethod(middleware1, middleware0) assert.Len(t, router.noMethod, 2) assert.Len(t, router.allNoMethod, 2) compareFunc(t, router.noMethod[0], middleware1) compareFunc(t, router.allNoMethod[0], middleware1) compareFunc(t, router.noMethod[1], middleware0) compareFunc(t, router.allNoMethod[1], middleware0) } func TestRebuild404Handlers(t *testing.T) { var middleware0 HandlerFunc = func(c *Context) {} var middleware1 HandlerFunc = func(c *Context) {} router := New() // Initially, allNoRoute should be nil assert.Nil(t, router.allNoRoute) // Set NoRoute handlers router.NoRoute(middleware0) assert.Len(t, router.allNoRoute, 1) assert.Len(t, router.noRoute, 1) compareFunc(t, router.allNoRoute[0], middleware0) // Add Use middleware should trigger rebuild404Handlers router.Use(middleware1) assert.Len(t, router.allNoRoute, 2) assert.Len(t, router.Handlers, 1) assert.Len(t, router.noRoute, 1) // Global middleware should come first compareFunc(t, router.allNoRoute[0], middleware1) compareFunc(t, router.allNoRoute[1], middleware0) } func TestNoMethodWithGlobalHandlers(t *testing.T) { var middleware0 HandlerFunc = func(c *Context) {} var middleware1 HandlerFunc = func(c *Context) {} var middleware2 HandlerFunc = func(c *Context) {} router := New() router.Use(middleware2) router.NoMethod(middleware0) assert.Len(t, router.allNoMethod, 2) assert.Len(t, router.Handlers, 1) assert.Len(t, router.noMethod, 1) compareFunc(t, router.Handlers[0], middleware2) compareFunc(t, router.noMethod[0], middleware0) compareFunc(t, router.allNoMethod[0], middleware2) compareFunc(t, router.allNoMethod[1], middleware0) router.Use(middleware1) assert.Len(t, router.allNoMethod, 3) assert.Len(t, router.Handlers, 2) assert.Len(t, router.noMethod, 1) compareFunc(t, router.Handlers[0], middleware2) compareFunc(t, router.Handlers[1], middleware1) compareFunc(t, router.noMethod[0], middleware0) compareFunc(t, router.allNoMethod[0], middleware2) compareFunc(t, router.allNoMethod[1], middleware1) compareFunc(t, router.allNoMethod[2], middleware0) } func compareFunc(t *testing.T, a, b any) { sf1 := reflect.ValueOf(a) sf2 := reflect.ValueOf(b) if sf1.Pointer() != sf2.Pointer() { t.Error("different functions") } } func TestListOfRoutes(t *testing.T) { router := New() router.GET("/favicon.ico", handlerTest1) router.GET("/", handlerTest1) group := router.Group("/users") { group.GET("/", handlerTest2) group.GET("/:id", handlerTest1) group.POST("/:id", handlerTest2) } router.Static("/static", ".") list := router.Routes() assert.Len(t, list, 7) assertRoutePresent(t, list, RouteInfo{ Method: http.MethodGet, Path: "/favicon.ico", Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest1$", }) assertRoutePresent(t, list, RouteInfo{ Method: http.MethodGet, Path: "/", Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest1$", }) assertRoutePresent(t, list, RouteInfo{ Method: http.MethodGet, Path: "/users/", Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest2$", }) assertRoutePresent(t, list, RouteInfo{ Method: http.MethodGet, Path: "/users/:id", Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest1$", }) assertRoutePresent(t, list, RouteInfo{ Method: http.MethodPost, Path: "/users/:id", Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest2$", }) } func TestEngineHandleContext(t *testing.T) { r := New() r.GET("/", func(c *Context) { c.Request.URL.Path = "/v2" r.HandleContext(c) }) v2 := r.Group("/v2") { v2.GET("/", func(c *Context) {}) } assert.NotPanics(t, func() { w := PerformRequest(r, http.MethodGet, "/") assert.Equal(t, 301, w.Code) }) } func TestEngineHandleContextManyReEntries(t *testing.T) { expectValue := 10000 var handlerCounter, middlewareCounter int64 r := New() r.Use(func(c *Context) { atomic.AddInt64(&middlewareCounter, 1) }) r.GET("/:count", func(c *Context) { countStr := c.Param("count") count, err := strconv.Atoi(countStr) require.NoError(t, err) n, err := c.Writer.Write([]byte(".")) require.NoError(t, err) assert.Equal(t, 1, n) switch { case count > 0: c.Request.URL.Path = "/" + strconv.Itoa(count-1) r.HandleContext(c) } }, func(c *Context) { atomic.AddInt64(&handlerCounter, 1) }) assert.NotPanics(t, func() { w := PerformRequest(r, http.MethodGet, "/"+strconv.Itoa(expectValue-1)) // include 0 value assert.Equal(t, 200, w.Code) assert.Equal(t, expectValue, w.Body.Len()) }) assert.Equal(t, int64(expectValue), handlerCounter) assert.Equal(t, int64(expectValue), middlewareCounter) } func TestEngineHandleContextPreventsMiddlewareReEntry(t *testing.T) { // given var handlerCounterV1, handlerCounterV2, middlewareCounterV1 int64 r := New() v1 := r.Group("/v1") { v1.Use(func(c *Context) { atomic.AddInt64(&middlewareCounterV1, 1) }) v1.GET("/test", func(c *Context) { atomic.AddInt64(&handlerCounterV1, 1) c.Status(http.StatusOK) }) } v2 := r.Group("/v2") { v2.GET("/test", func(c *Context) { c.Request.URL.Path = "/v1/test" r.HandleContext(c) }, func(c *Context) { atomic.AddInt64(&handlerCounterV2, 1) }) } // when responseV1 := PerformRequest(r, "GET", "/v1/test") responseV2 := PerformRequest(r, "GET", "/v2/test") // then assert.Equal(t, 200, responseV1.Code) assert.Equal(t, 200, responseV2.Code) assert.Equal(t, int64(2), handlerCounterV1) assert.Equal(t, int64(2), middlewareCounterV1) assert.Equal(t, int64(1), handlerCounterV2) } func TestEngineHandleContextUseEscapedPathPercentEncoded(t *testing.T) { r := New() r.UseEscapedPath = true r.UnescapePathValues = false r.GET("/v1/:path", func(c *Context) { // Path is Escaped, the %25 is not interpreted as % assert.Equal(t, "foo%252Fbar", c.Param("path")) c.Status(http.StatusOK) }) req := httptest.NewRequest(http.MethodGet, "/v1/foo%252Fbar", nil) w := httptest.NewRecorder() r.ServeHTTP(w, req) } func TestEngineHandleContextUseRawPathPercentEncoded(t *testing.T) { r := New() r.UseRawPath = true r.UnescapePathValues = false r.GET("/v1/:path", func(c *Context) { // Path is used, the %25 is interpreted as % assert.Equal(t, "foo%2Fbar", c.Param("path")) c.Status(http.StatusOK) }) req := httptest.NewRequest(http.MethodGet, "/v1/foo%252Fbar", nil) w := httptest.NewRecorder() r.ServeHTTP(w, req) } func TestEngineHandleContextUseEscapedPathOverride(t *testing.T) { r := New() r.UseEscapedPath = true r.UseRawPath = true r.UnescapePathValues = false r.GET("/v1/:path", func(c *Context) { assert.Equal(t, "foo%25bar", c.Param("path")) c.Status(http.StatusOK) }) assert.NotPanics(t, func() { w := PerformRequest(r, http.MethodGet, "/v1/foo%25bar") assert.Equal(t, 200, w.Code) }) } func TestPrepareTrustedCIRDsWith(t *testing.T) { r := New() // valid ipv4 cidr { expectedTrustedCIDRs := []*net.IPNet{parseCIDR("0.0.0.0/0")} err := r.SetTrustedProxies([]string{"0.0.0.0/0"}) require.NoError(t, err) assert.Equal(t, expectedTrustedCIDRs, r.trustedCIDRs) } // invalid ipv4 cidr { err := r.SetTrustedProxies([]string{"192.168.1.33/33"}) require.Error(t, err) } // valid ipv4 address { expectedTrustedCIDRs := []*net.IPNet{parseCIDR("192.168.1.33/32")} err := r.SetTrustedProxies([]string{"192.168.1.33"}) require.NoError(t, err) assert.Equal(t, expectedTrustedCIDRs, r.trustedCIDRs) } // invalid ipv4 address { err := r.SetTrustedProxies([]string{"192.168.1.256"}) require.Error(t, err) } // valid ipv6 address { expectedTrustedCIDRs := []*net.IPNet{parseCIDR("2002:0000:0000:1234:abcd:ffff:c0a8:0101/128")} err := r.SetTrustedProxies([]string{"2002:0000:0000:1234:abcd:ffff:c0a8:0101"}) require.NoError(t, err) assert.Equal(t, expectedTrustedCIDRs, r.trustedCIDRs) } // invalid ipv6 address { err := r.SetTrustedProxies([]string{"gggg:0000:0000:1234:abcd:ffff:c0a8:0101"}) require.Error(t, err) } // valid ipv6 cidr { expectedTrustedCIDRs := []*net.IPNet{parseCIDR("::/0")} err := r.SetTrustedProxies([]string{"::/0"}) require.NoError(t, err) assert.Equal(t, expectedTrustedCIDRs, r.trustedCIDRs) } // invalid ipv6 cidr { err := r.SetTrustedProxies([]string{"gggg:0000:0000:1234:abcd:ffff:c0a8:0101/129"}) require.Error(t, err) } // valid combination { expectedTrustedCIDRs := []*net.IPNet{ parseCIDR("::/0"), parseCIDR("192.168.0.0/16"), parseCIDR("172.16.0.1/32"), } err := r.SetTrustedProxies([]string{ "::/0", "192.168.0.0/16", "172.16.0.1", }) require.NoError(t, err) assert.Equal(t, expectedTrustedCIDRs, r.trustedCIDRs) } // invalid combination { err := r.SetTrustedProxies([]string{ "::/0", "192.168.0.0/16", "172.16.0.256", }) require.Error(t, err) } // nil value { err := r.SetTrustedProxies(nil) assert.Nil(t, r.trustedCIDRs) require.NoError(t, err) } } func parseCIDR(cidr string) *net.IPNet { _, parsedCIDR, err := net.ParseCIDR(cidr) if err != nil { fmt.Println(err) } return parsedCIDR } func assertRoutePresent(t *testing.T, gotRoutes RoutesInfo, wantRoute RouteInfo) { for _, gotRoute := range gotRoutes { if gotRoute.Path == wantRoute.Path && gotRoute.Method == wantRoute.Method { assert.Regexp(t, wantRoute.Handler, gotRoute.Handler) return } } t.Errorf("route not found: %v", wantRoute) } func handlerTest1(c *Context) {} func handlerTest2(c *Context) {} func TestNewOptionFunc(t *testing.T) { fc := func(e *Engine) { e.GET("/test1", handlerTest1) e.GET("/test2", handlerTest2) e.Use(func(c *Context) { c.Next() }) } r := New(fc) routes := r.Routes() assertRoutePresent(t, routes, RouteInfo{Path: "/test1", Method: http.MethodGet, Handler: "github.com/gin-gonic/gin.handlerTest1"}) assertRoutePresent(t, routes, RouteInfo{Path: "/test2", Method: http.MethodGet, Handler: "github.com/gin-gonic/gin.handlerTest2"}) } func TestWithOptionFunc(t *testing.T) { r := New() r.With(func(e *Engine) { e.GET("/test1", handlerTest1) e.GET("/test2", handlerTest2) e.Use(func(c *Context) { c.Next() }) }) routes := r.Routes() assertRoutePresent(t, routes, RouteInfo{Path: "/test1", Method: http.MethodGet, Handler: "github.com/gin-gonic/gin.handlerTest1"}) assertRoutePresent(t, routes, RouteInfo{Path: "/test2", Method: http.MethodGet, Handler: "github.com/gin-gonic/gin.handlerTest2"}) } type Birthday string func (b *Birthday) UnmarshalParam(param string) error { *b = Birthday(strings.ReplaceAll(param, "-", "/")) return nil } func TestCustomUnmarshalStruct(t *testing.T) { route := Default() var request struct { Birthday Birthday `form:"birthday"` } route.GET("/test", func(ctx *Context) { _ = ctx.BindQuery(&request) ctx.JSON(200, request.Birthday) }) req := httptest.NewRequest(http.MethodGet, "/test?birthday=2000-01-01", nil) w := httptest.NewRecorder() route.ServeHTTP(w, req) assert.Equal(t, 200, w.Code) assert.Equal(t, `"2000/01/01"`, w.Body.String()) } // Test the fix for https://github.com/gin-gonic/gin/issues/4002 func TestMethodNotAllowedNoRoute(t *testing.T) { g := New() g.HandleMethodNotAllowed = true req := httptest.NewRequest(http.MethodGet, "/", nil) resp := httptest.NewRecorder() assert.NotPanics(t, func() { g.ServeHTTP(resp, req) }) assert.Equal(t, http.StatusNotFound, resp.Code) } // Test the fix for https://github.com/gin-gonic/gin/pull/4415 func TestLiteralColonWithRun(t *testing.T) { SetMode(TestMode) router := New() router.GET(`/test\:action`, func(c *Context) { c.JSON(http.StatusOK, H{"path": "literal_colon"}) }) router.updateRouteTrees() w := httptest.NewRecorder() req, _ := http.NewRequest(http.MethodGet, "/test:action", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Contains(t, w.Body.String(), "literal_colon") } func TestLiteralColonWithDirectServeHTTP(t *testing.T) { SetMode(TestMode) router := New() router.GET(`/test\:action`, func(c *Context) { c.JSON(http.StatusOK, H{"path": "literal_colon"}) }) w := httptest.NewRecorder() req, _ := http.NewRequest(http.MethodGet, "/test:action", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Contains(t, w.Body.String(), "literal_colon") } func TestLiteralColonWithHandler(t *testing.T) { SetMode(TestMode) router := New() router.GET(`/test\:action`, func(c *Context) { c.JSON(http.StatusOK, H{"path": "literal_colon"}) }) handler := router.Handler() w := httptest.NewRecorder() req, _ := http.NewRequest(http.MethodGet, "/test:action", nil) handler.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Contains(t, w.Body.String(), "literal_colon") } func TestLiteralColonWithHTTPServer(t *testing.T) { SetMode(TestMode) router := New() router.GET(`/test\:action`, func(c *Context) { c.JSON(http.StatusOK, H{"path": "literal_colon"}) }) router.GET("/test/:param", func(c *Context) { c.JSON(http.StatusOK, H{"param": c.Param("param")}) }) w := httptest.NewRecorder() req, _ := http.NewRequest(http.MethodGet, "/test:action", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Contains(t, w.Body.String(), "literal_colon") w2 := httptest.NewRecorder() req2, _ := http.NewRequest(http.MethodGet, "/test/foo", nil) router.ServeHTTP(w2, req2) assert.Equal(t, http.StatusOK, w2.Code) assert.Contains(t, w2.Body.String(), "foo") } // Test that updateRouteTrees is called only once func TestUpdateRouteTreesCalledOnce(t *testing.T) { SetMode(TestMode) router := New() router.GET(`/test\:action`, func(c *Context) { c.String(http.StatusOK, "ok") }) for range 5 { w := httptest.NewRecorder() req, _ := http.NewRequest(http.MethodGet, "/test:action", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "ok", w.Body.String()) } }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/deprecated.go
deprecated.go
// 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 gin import ( "log" "github.com/gin-gonic/gin/binding" ) // BindWith binds the passed struct pointer using the specified binding engine. // See the binding package. // // Deprecated: Use MustBindWith or ShouldBindWith. func (c *Context) BindWith(obj any, b binding.Binding) error { log.Println(`BindWith(\"any, binding.Binding\") error is going to be deprecated, please check issue #662 and either use MustBindWith() if you want HTTP 400 to be automatically returned if any error occur, or use ShouldBindWith() if you need to manage the error.`) return c.MustBindWith(obj, b) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/routes_test.go
routes_test.go
// 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 gin import ( "fmt" "net/http" "net/http/httptest" "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) type header struct { Key string Value string } // PerformRequest for testing gin router. func PerformRequest(r http.Handler, method, path string, headers ...header) *httptest.ResponseRecorder { req := httptest.NewRequest(method, path, nil) for _, h := range headers { req.Header.Add(h.Key, h.Value) } w := httptest.NewRecorder() r.ServeHTTP(w, req) return w } func testRouteOK(method string, t *testing.T) { passed := false passedAny := false r := New() r.Any("/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 tests that POST route is correctly invoked. func testRouteNotOK(method string, t *testing.T) { passed := false router := New() router.Handle(method, "/test_2", func(c *Context) { passed = true }) 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, 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", func(c *Context) { passed = true }) w := PerformRequest(router, method, "/test") assert.False(t, passed) assert.Equal(t, http.StatusMethodNotAllowed, w.Code) } func TestRouterMethod(t *testing.T) { router := New() router.PUT("/hey2", func(c *Context) { c.String(http.StatusOK, "sup2") }) router.PUT("/hey", func(c *Context) { c.String(http.StatusOK, "called") }) router.PUT("/hey3", func(c *Context) { c.String(http.StatusOK, "sup3") }) w := PerformRequest(router, http.MethodPut, "/hey") assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "called", w.Body.String()) } func TestRouterGroupRouteOK(t *testing.T) { testRouteOK(http.MethodGet, t) testRouteOK(http.MethodPost, t) testRouteOK(http.MethodPut, t) testRouteOK(http.MethodPatch, t) testRouteOK(http.MethodHead, t) testRouteOK(http.MethodOptions, t) testRouteOK(http.MethodDelete, t) testRouteOK(http.MethodConnect, t) testRouteOK(http.MethodTrace, t) } func TestRouteNotOK(t *testing.T) { testRouteNotOK(http.MethodGet, t) testRouteNotOK(http.MethodPost, t) testRouteNotOK(http.MethodPut, t) testRouteNotOK(http.MethodPatch, t) testRouteNotOK(http.MethodHead, t) testRouteNotOK(http.MethodOptions, t) testRouteNotOK(http.MethodDelete, t) testRouteNotOK(http.MethodConnect, t) testRouteNotOK(http.MethodTrace, t) } func TestRouteNotOK2(t *testing.T) { testRouteNotOK2(http.MethodGet, t) testRouteNotOK2(http.MethodPost, t) testRouteNotOK2(http.MethodPut, t) testRouteNotOK2(http.MethodPatch, t) testRouteNotOK2(http.MethodHead, t) testRouteNotOK2(http.MethodOptions, t) testRouteNotOK2(http.MethodDelete, t) testRouteNotOK2(http.MethodConnect, t) testRouteNotOK2(http.MethodTrace, t) } func TestRouteRedirectTrailingSlash(t *testing.T) { router := New() router.RedirectFixedPath = false router.RedirectTrailingSlash = true router.GET("/path", func(c *Context) {}) router.GET("/path2/", func(c *Context) {}) router.POST("/path3", func(c *Context) {}) router.PUT("/path4/", func(c *Context) {}) w := PerformRequest(router, http.MethodGet, "/path/") assert.Equal(t, "/path", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodGet, "/path2") assert.Equal(t, "/path2/", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodPost, "/path3/") assert.Equal(t, "/path3", w.Header().Get("Location")) assert.Equal(t, http.StatusTemporaryRedirect, w.Code) w = PerformRequest(router, http.MethodPut, "/path4") assert.Equal(t, "/path4/", w.Header().Get("Location")) assert.Equal(t, http.StatusTemporaryRedirect, w.Code) w = PerformRequest(router, http.MethodGet, "/path") assert.Equal(t, http.StatusOK, w.Code) w = PerformRequest(router, http.MethodGet, "/path2/") assert.Equal(t, http.StatusOK, w.Code) w = PerformRequest(router, http.MethodPost, "/path3") assert.Equal(t, http.StatusOK, w.Code) w = PerformRequest(router, http.MethodPut, "/path4/") assert.Equal(t, http.StatusOK, w.Code) w = PerformRequest(router, http.MethodGet, "/path2", header{Key: "X-Forwarded-Prefix", Value: "/api"}) assert.Equal(t, "/api/path2/", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodGet, "/path2/", header{Key: "X-Forwarded-Prefix", Value: "/api/"}) assert.Equal(t, http.StatusOK, w.Code) w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "../../api#?"}) assert.Equal(t, "/api/path", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "../../api"}) assert.Equal(t, "/api/path", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodGet, "/path2", header{Key: "X-Forwarded-Prefix", Value: "../../api"}) assert.Equal(t, "/api/path2/", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodGet, "/path2", header{Key: "X-Forwarded-Prefix", Value: "/../../api"}) assert.Equal(t, "/api/path2/", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "api/../../"}) assert.Equal(t, "//path", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "api/../../../"}) assert.Equal(t, "/path", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodGet, "/path2", header{Key: "X-Forwarded-Prefix", Value: "../../gin-gonic.com"}) assert.Equal(t, "/gin-goniccom/path2/", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodGet, "/path2", header{Key: "X-Forwarded-Prefix", Value: "/../../gin-gonic.com"}) assert.Equal(t, "/gin-goniccom/path2/", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "https://gin-gonic.com/#"}) assert.Equal(t, "https/gin-goniccom/https/gin-goniccom/path", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "#api"}) assert.Equal(t, "api/api/path", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "/nor-mal/#?a=1"}) assert.Equal(t, "/nor-mal/a1/path", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "/nor-mal/%2e%2e/"}) assert.Equal(t, "/nor-mal/2e2e/path", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) router.RedirectTrailingSlash = false w = PerformRequest(router, http.MethodGet, "/path/") assert.Equal(t, http.StatusNotFound, w.Code) w = PerformRequest(router, http.MethodGet, "/path2") assert.Equal(t, http.StatusNotFound, w.Code) w = PerformRequest(router, http.MethodPost, "/path3/") assert.Equal(t, http.StatusNotFound, w.Code) w = PerformRequest(router, http.MethodPut, "/path4") assert.Equal(t, http.StatusNotFound, w.Code) } func TestRouteRedirectFixedPath(t *testing.T) { router := New() router.RedirectFixedPath = true router.RedirectTrailingSlash = false router.GET("/path", func(c *Context) {}) router.GET("/Path2", func(c *Context) {}) router.POST("/PATH3", func(c *Context) {}) router.POST("/Path4/", func(c *Context) {}) w := PerformRequest(router, http.MethodGet, "/PATH") assert.Equal(t, "/path", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodGet, "/path2") assert.Equal(t, "/Path2", w.Header().Get("Location")) assert.Equal(t, http.StatusMovedPermanently, w.Code) w = PerformRequest(router, http.MethodPost, "/path3") assert.Equal(t, "/PATH3", w.Header().Get("Location")) assert.Equal(t, http.StatusTemporaryRedirect, w.Code) w = PerformRequest(router, http.MethodPost, "/path4") assert.Equal(t, "/Path4/", w.Header().Get("Location")) assert.Equal(t, http.StatusTemporaryRedirect, w.Code) } // TestContextParamsGet tests that a parameter can be parsed from the URL. func TestRouteParamsByName(t *testing.T) { name := "" lastName := "" wild := "" router := New() router.GET("/test/:name/:last_name/*wild", func(c *Context) { name = c.Params.ByName("name") lastName = c.Params.ByName("last_name") var ok bool wild, ok = c.Params.Get("wild") assert.True(t, ok) assert.Equal(t, name, c.Param("name")) assert.Equal(t, lastName, c.Param("last_name")) assert.Empty(t, c.Param("wtf")) assert.Empty(t, c.Params.ByName("wtf")) wtf, ok := c.Params.Get("wtf") assert.Empty(t, wtf) assert.False(t, ok) }) w := PerformRequest(router, http.MethodGet, "/test/john/smith/is/super/great") assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "john", name) assert.Equal(t, "smith", lastName) assert.Equal(t, "/is/super/great", wild) } // TestContextParamsGet tests that a parameter can be parsed from the URL even with extra slashes. func TestRouteParamsByNameWithExtraSlash(t *testing.T) { name := "" lastName := "" wild := "" router := New() router.RemoveExtraSlash = true router.GET("/test/:name/:last_name/*wild", func(c *Context) { name = c.Params.ByName("name") lastName = c.Params.ByName("last_name") var ok bool wild, ok = c.Params.Get("wild") assert.True(t, ok) assert.Equal(t, name, c.Param("name")) assert.Equal(t, lastName, c.Param("last_name")) assert.Empty(t, c.Param("wtf")) assert.Empty(t, c.Params.ByName("wtf")) wtf, ok := c.Params.Get("wtf") assert.Empty(t, wtf) assert.False(t, ok) }) w := PerformRequest(router, http.MethodGet, "//test//john//smith//is//super//great") assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "john", name) assert.Equal(t, "smith", lastName) assert.Equal(t, "/is/super/great", wild) } // TestRouteParamsNotEmpty tests that context parameters will be set // even if a route with params/wildcards is registered after the context // initialisation (which happened in a previous requests). func TestRouteParamsNotEmpty(t *testing.T) { name := "" lastName := "" wild := "" router := New() w := PerformRequest(router, http.MethodGet, "/test/john/smith/is/super/great") assert.Equal(t, http.StatusNotFound, w.Code) router.GET("/test/:name/:last_name/*wild", func(c *Context) { name = c.Params.ByName("name") lastName = c.Params.ByName("last_name") var ok bool wild, ok = c.Params.Get("wild") assert.True(t, ok) assert.Equal(t, name, c.Param("name")) assert.Equal(t, lastName, c.Param("last_name")) assert.Empty(t, c.Param("wtf")) assert.Empty(t, c.Params.ByName("wtf")) wtf, ok := c.Params.Get("wtf") assert.Empty(t, wtf) assert.False(t, ok) }) w = PerformRequest(router, http.MethodGet, "/test/john/smith/is/super/great") assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "john", name) assert.Equal(t, "smith", lastName) assert.Equal(t, "/is/super/great", wild) } // TestHandleStaticFile - ensure the static file handles properly func TestRouteStaticFile(t *testing.T) { // SETUP file testRoot, _ := os.Getwd() f, err := os.CreateTemp(testRoot, "") if err != nil { t.Error(err) } defer os.Remove(f.Name()) _, err = f.WriteString("Gin Web Framework") require.NoError(t, err) f.Close() dir, filename := filepath.Split(f.Name()) // SETUP gin router := New() router.Static("/using_static", dir) router.StaticFile("/result", f.Name()) w := PerformRequest(router, http.MethodGet, "/using_static/"+filename) w2 := PerformRequest(router, http.MethodGet, "/result") assert.Equal(t, w, w2) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "Gin Web Framework", w.Body.String()) assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) w3 := PerformRequest(router, http.MethodHead, "/using_static/"+filename) w4 := PerformRequest(router, http.MethodHead, "/result") assert.Equal(t, w3, w4) assert.Equal(t, http.StatusOK, w3.Code) } // TestHandleStaticFile - ensure the static file handles properly func TestRouteStaticFileFS(t *testing.T) { // SETUP file testRoot, _ := os.Getwd() f, err := os.CreateTemp(testRoot, "") if err != nil { t.Error(err) } defer os.Remove(f.Name()) _, err = f.WriteString("Gin Web Framework") require.NoError(t, err) f.Close() dir, filename := filepath.Split(f.Name()) // SETUP gin router := New() router.Static("/using_static", dir) router.StaticFileFS("/result_fs", filename, Dir(dir, false)) w := PerformRequest(router, http.MethodGet, "/using_static/"+filename) w2 := PerformRequest(router, http.MethodGet, "/result_fs") assert.Equal(t, w, w2) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "Gin Web Framework", w.Body.String()) assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) w3 := PerformRequest(router, http.MethodHead, "/using_static/"+filename) w4 := PerformRequest(router, http.MethodHead, "/result_fs") assert.Equal(t, w3, w4) assert.Equal(t, http.StatusOK, w3.Code) } // TestHandleStaticDir - ensure the root/sub dir handles properly func TestRouteStaticListingDir(t *testing.T) { router := New() router.StaticFS("/", Dir("./", true)) w := PerformRequest(router, http.MethodGet, "/") assert.Equal(t, http.StatusOK, w.Code) assert.Contains(t, w.Body.String(), "gin.go") assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } // TestHandleHeadToDir - ensure the root/sub dir handles properly func TestRouteStaticNoListing(t *testing.T) { router := New() router.Static("/", "./") w := PerformRequest(router, http.MethodGet, "/") assert.Equal(t, http.StatusNotFound, w.Code) assert.NotContains(t, w.Body.String(), "gin.go") } func TestRouterMiddlewareAndStatic(t *testing.T) { router := New() static := router.Group("/", func(c *Context) { c.Writer.Header().Add("Last-Modified", "Mon, 02 Jan 2006 15:04:05 MST") c.Writer.Header().Add("Expires", "Mon, 02 Jan 2006 15:04:05 MST") c.Writer.Header().Add("X-GIN", "Gin Framework") }) static.Static("/", "./") w := PerformRequest(router, http.MethodGet, "/gin.go") assert.Equal(t, http.StatusOK, w.Code) assert.Contains(t, w.Body.String(), "package gin") // Content-Type='text/plain; charset=utf-8' when go version <= 1.16, // else, Content-Type='text/x-go; charset=utf-8' assert.NotEmpty(t, w.Header().Get("Content-Type")) assert.NotEqual(t, "Mon, 02 Jan 2006 15:04:05 MST", w.Header().Get("Last-Modified")) assert.Equal(t, "Mon, 02 Jan 2006 15:04:05 MST", w.Header().Get("Expires")) assert.Equal(t, "Gin Framework", w.Header().Get("x-GIN")) } func TestRouteNotAllowedEnabled(t *testing.T) { router := New() router.HandleMethodNotAllowed = true router.POST("/path", func(c *Context) {}) w := PerformRequest(router, http.MethodGet, "/path") assert.Equal(t, http.StatusMethodNotAllowed, w.Code) router.NoMethod(func(c *Context) { c.String(http.StatusTeapot, "responseText") }) w = PerformRequest(router, http.MethodGet, "/path") assert.Equal(t, "responseText", w.Body.String()) assert.Equal(t, http.StatusTeapot, w.Code) } func TestRouteNotAllowedEnabled2(t *testing.T) { router := New() router.HandleMethodNotAllowed = true // add one methodTree to trees router.addRoute(http.MethodPost, "/", HandlersChain{func(_ *Context) {}}) router.GET("/path2", func(c *Context) {}) w := PerformRequest(router, http.MethodPost, "/path2") assert.Equal(t, http.StatusMethodNotAllowed, w.Code) } func TestRouteNotAllowedEnabled3(t *testing.T) { router := New() router.HandleMethodNotAllowed = true router.GET("/path", func(c *Context) {}) router.POST("/path", func(c *Context) {}) w := PerformRequest(router, http.MethodPut, "/path") assert.Equal(t, http.StatusMethodNotAllowed, w.Code) allowed := w.Header().Get("Allow") assert.Contains(t, allowed, http.MethodGet) assert.Contains(t, allowed, http.MethodPost) } func TestRouteNotAllowedDisabled(t *testing.T) { router := New() router.HandleMethodNotAllowed = false router.POST("/path", func(c *Context) {}) w := PerformRequest(router, http.MethodGet, "/path") assert.Equal(t, http.StatusNotFound, w.Code) router.NoMethod(func(c *Context) { c.String(http.StatusTeapot, "responseText") }) w = PerformRequest(router, http.MethodGet, "/path") assert.Equal(t, "404 page not found", w.Body.String()) assert.Equal(t, http.StatusNotFound, w.Code) } func TestRouterNotFoundWithRemoveExtraSlash(t *testing.T) { router := New() router.RemoveExtraSlash = true router.GET("/path", func(c *Context) {}) router.GET("/", func(c *Context) {}) testRoutes := []struct { route string code int location string }{ {"/../path", http.StatusOK, ""}, // CleanPath {"/nope", http.StatusNotFound, ""}, // NotFound } for _, tr := range testRoutes { w := PerformRequest(router, http.MethodGet, tr.route) assert.Equal(t, tr.code, w.Code) if w.Code != http.StatusNotFound { assert.Equal(t, tr.location, w.Header().Get("Location")) } } } func TestRouterNotFound(t *testing.T) { router := New() router.RedirectFixedPath = true router.GET("/path", func(c *Context) {}) router.GET("/dir/", func(c *Context) {}) router.GET("/", func(c *Context) {}) testRoutes := []struct { route string code int location string }{ {"/path/", http.StatusMovedPermanently, "/path"}, // TSR -/ {"/dir", http.StatusMovedPermanently, "/dir/"}, // TSR +/ {"/PATH", http.StatusMovedPermanently, "/path"}, // Fixed Case {"/DIR/", http.StatusMovedPermanently, "/dir/"}, // Fixed Case {"/PATH/", http.StatusMovedPermanently, "/path"}, // Fixed Case -/ {"/DIR", http.StatusMovedPermanently, "/dir/"}, // Fixed Case +/ {"/../path", http.StatusMovedPermanently, "/path"}, // Without CleanPath {"/nope", http.StatusNotFound, ""}, // NotFound } for _, tr := range testRoutes { w := PerformRequest(router, http.MethodGet, tr.route) assert.Equal(t, tr.code, w.Code) if w.Code != http.StatusNotFound { assert.Equal(t, tr.location, w.Header().Get("Location")) } } // Test custom not found handler var notFound bool router.NoRoute(func(c *Context) { c.AbortWithStatus(http.StatusNotFound) notFound = true }) w := PerformRequest(router, http.MethodGet, "/nope") assert.Equal(t, http.StatusNotFound, w.Code) assert.True(t, notFound) // Test other method than GET (want 307 instead of 301) router.PATCH("/path", func(c *Context) {}) w = PerformRequest(router, http.MethodPatch, "/path/") assert.Equal(t, http.StatusTemporaryRedirect, w.Code) assert.Equal(t, "map[Location:[/path]]", fmt.Sprint(w.Header())) // Test special case where no node for the prefix "/" exists router = New() router.GET("/a", func(c *Context) {}) w = PerformRequest(router, http.MethodGet, "/") assert.Equal(t, http.StatusNotFound, w.Code) // Reproduction test for the bug of issue #2843 router = New() router.NoRoute(func(c *Context) { if c.Request.RequestURI == "/login" { c.String(http.StatusOK, "login") } }) router.GET("/logout", func(c *Context) { c.String(http.StatusOK, "logout") }) w = PerformRequest(router, http.MethodGet, "/login") assert.Equal(t, "login", w.Body.String()) w = PerformRequest(router, http.MethodGet, "/logout") assert.Equal(t, "logout", w.Body.String()) } func TestRouterStaticFSNotFound(t *testing.T) { router := New() router.StaticFS("/", http.FileSystem(http.Dir("/thisreallydoesntexist/"))) router.NoRoute(func(c *Context) { c.String(http.StatusNotFound, "non existent") }) w := PerformRequest(router, http.MethodGet, "/nonexistent") assert.Equal(t, "non existent", w.Body.String()) w = PerformRequest(router, http.MethodHead, "/nonexistent") assert.Equal(t, "non existent", w.Body.String()) } func TestRouterStaticFSFileNotFound(t *testing.T) { router := New() router.StaticFS("/", http.FileSystem(http.Dir("."))) assert.NotPanics(t, func() { PerformRequest(router, http.MethodGet, "/nonexistent") }) } // Reproduction test for the bug of issue #1805 func TestMiddlewareCalledOnceByRouterStaticFSNotFound(t *testing.T) { router := New() // Middleware must be called just only once by per request. middlewareCalledNum := 0 router.Use(func(c *Context) { middlewareCalledNum++ }) router.StaticFS("/", http.FileSystem(http.Dir("/thisreallydoesntexist/"))) // First access PerformRequest(router, http.MethodGet, "/nonexistent") assert.Equal(t, 1, middlewareCalledNum) // Second access PerformRequest(router, http.MethodHead, "/nonexistent") assert.Equal(t, 2, middlewareCalledNum) } func TestRouteRawPath(t *testing.T) { route := New() route.UseRawPath = true route.POST("/project/:name/build/:num", func(c *Context) { name := c.Params.ByName("name") num := c.Params.ByName("num") assert.Equal(t, name, c.Param("name")) assert.Equal(t, num, c.Param("num")) assert.Equal(t, "Some/Other/Project", name) assert.Equal(t, "222", num) }) w := PerformRequest(route, http.MethodPost, "/project/Some%2FOther%2FProject/build/222") assert.Equal(t, http.StatusOK, w.Code) } func TestRouteRawPathNoUnescape(t *testing.T) { route := New() route.UseRawPath = true route.UnescapePathValues = false route.POST("/project/:name/build/:num", func(c *Context) { name := c.Params.ByName("name") num := c.Params.ByName("num") assert.Equal(t, name, c.Param("name")) assert.Equal(t, num, c.Param("num")) assert.Equal(t, "Some%2FOther%2FProject", name) assert.Equal(t, "333", num) }) w := PerformRequest(route, http.MethodPost, "/project/Some%2FOther%2FProject/build/333") assert.Equal(t, http.StatusOK, w.Code) } func TestRouteServeErrorWithWriteHeader(t *testing.T) { route := New() route.Use(func(c *Context) { c.Status(http.StatusMisdirectedRequest) c.Next() }) w := PerformRequest(route, http.MethodGet, "/NotFound") assert.Equal(t, http.StatusMisdirectedRequest, w.Code) assert.Equal(t, 0, w.Body.Len()) } func TestRouteContextHoldsFullPath(t *testing.T) { router := New() // Test routes routes := []string{ "/simple", "/project/:name", "/", "/news/home", "/news", "/simple-two/one", "/simple-two/one-two", "/project/:name/build/*params", "/project/:name/bui", "/user/:id/status", "/user/:id", "/user/:id/profile", } for _, route := range routes { actualRoute := route router.GET(route, func(c *Context) { // For each defined route context should contain its full path assert.Equal(t, actualRoute, c.FullPath()) c.AbortWithStatus(http.StatusOK) }) } for _, route := range routes { w := PerformRequest(router, http.MethodGet, route) assert.Equal(t, http.StatusOK, w.Code) } // Test not found router.Use(func(c *Context) { // For not found routes full path is empty assert.Empty(t, c.FullPath()) }) w := PerformRequest(router, http.MethodGet, "/not-found") assert.Equal(t, http.StatusNotFound, w.Code) } func TestEngineHandleMethodNotAllowedCornerCase(t *testing.T) { r := New() r.HandleMethodNotAllowed = true base := r.Group("base") base.GET("/metrics", handlerTest1) v1 := base.Group("v1") v1.GET("/:id/devices", handlerTest1) v1.GET("/user/:id/groups", handlerTest1) v1.GET("/orgs/:id", handlerTest1) v1.DELETE("/orgs/:id", handlerTest1) w := PerformRequest(r, http.MethodGet, "/base/v1/user/groups") assert.Equal(t, http.StatusNotFound, w.Code) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/tree.go
tree.go
// Copyright 2013 Julien Schmidt. All rights reserved. // 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 ( "net/url" "strings" "unicode" "unicode/utf8" "github.com/gin-gonic/gin/internal/bytesconv" ) // Param is a single URL parameter, consisting of a key and a value. type Param struct { Key string Value string } // Params is a Param-slice, as returned by the router. // The slice is ordered, the first URL parameter is also the first slice value. // It is therefore safe to read values by the index. type Params []Param // Get returns the value of the first Param which key matches the given name and a boolean true. // If no matching Param is found, an empty string is returned and 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 returned. func (ps Params) ByName(name string) (va string) { va, _ = ps.Get(name) return } type methodTree struct { method string root *node } type methodTrees []methodTree func (trees methodTrees) 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_ && 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 = append(n.children[:len(n.children)-1], child, wildcardChild) } else { n.children = append(n.children, child) } } func countParams(path string) uint16 { colons := strings.Count(path, ":") stars := strings.Count(path, "*") return safeUint16(colons + stars) } func countSections(path string) uint16 { return safeUint16(strings.Count(path, "/")) } type nodeType uint8 const ( static nodeType = iota root param catchAll ) type node struct { path string indices string wildChild bool nType nodeType priority uint32 children []*node // child nodes, at most 1 :param style node at the end of the array handlers HandlersChain fullPath string } // Increments priority of the given child and reorders if necessary func (n *node) incrementChildPrio(pos int) int { cs := n.children cs[pos].priority++ prio := cs[pos].priority // Adjust position (move to front) newPos := pos for ; newPos > 0 && cs[newPos-1].priority < prio; newPos-- { // Swap node positions cs[newPos-1], cs[newPos] = cs[newPos], cs[newPos-1] } // Build new index char string if newPos != pos { n.indices = n.indices[:newPos] + // Unchanged prefix, might be empty n.indices[pos:pos+1] + // The index char we move n.indices[newPos:pos] + n.indices[pos+1:] // Rest without char at 'pos' } return newPos } // addRoute adds a node with the given handle to the path. // Not concurrency-safe! func (n *node) addRoute(path string, handlers HandlersChain) { fullPath := path n.priority++ // Empty tree if len(n.path) == 0 && len(n.children) == 0 { n.insertChild(path, fullPath, handlers) n.nType = root return } parentFullPathIndex := 0 walk: for { // Find the longest common prefix. // This also implies that the common prefix contains no ':' or '*' // since the existing key can't contain those chars. i := longestCommonPrefix(path, n.path) // Split edge if i < len(n.path) { child := node{ path: n.path[i:], wildChild: n.wildChild, nType: static, indices: n.indices, children: n.children, handlers: n.handlers, priority: n.priority - 1, fullPath: n.fullPath, } n.children = []*node{&child} // []byte for proper unicode char conversion, see #65 n.indices = bytesconv.BytesToString([]byte{n.path[i]}) n.path = path[:i] n.handlers = nil n.wildChild = false n.fullPath = fullPath[:parentFullPathIndex+i] } // Make new node a child of this node if i < len(path) { path = path[i:] c := path[0] // '/' after param if n.nType == param && c == '/' && len(n.children) == 1 { parentFullPathIndex += len(n.path) n = n.children[0] n.priority++ continue walk } // Check if a child with the next path byte exists for i, max_ := 0, len(n.indices); i < max_; i++ { if c == n.indices[i] { parentFullPathIndex += len(n.path) i = n.incrementChildPrio(i) n = n.children[i] continue walk } } // Otherwise insert it if c != ':' && c != '*' && n.nType != catchAll { // []byte for proper unicode char conversion, see #65 n.indices += bytesconv.BytesToString([]byte{c}) child := &node{ fullPath: fullPath, } n.addChild(child) n.incrementChildPrio(len(n.indices) - 1) n = child } else if n.wildChild { // inserting a wildcard node, need to check if it conflicts with the existing wildcard n = n.children[len(n.children)-1] n.priority++ // Check if the wildcard matches if len(path) >= len(n.path) && n.path == path[:len(n.path)] && // Adding a child to a catchAll is not possible n.nType != catchAll && // Check for longer wildcard, e.g. :name and :names (len(n.path) >= len(path) || path[len(n.path)] == '/') { continue walk } // Wildcard conflict pathSeg := path if n.nType != catchAll { pathSeg, _, _ = strings.Cut(pathSeg, "/") } prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path panic("'" + pathSeg + "' in new path '" + fullPath + "' conflicts with existing wildcard '" + n.path + "' in existing prefix '" + prefix + "'") } n.insertChild(path, fullPath, handlers) return } // Otherwise add handle to current node if n.handlers != nil { panic("handlers are already registered for path '" + fullPath + "'") } n.handlers = handlers n.fullPath = fullPath return } } // Search for a wildcard segment and check the name for invalid characters. // Returns -1 as index, if no wildcard was found. func findWildcard(path string) (wildcard string, i int, valid bool) { // Find start escapeColon := false for start, c := range []byte(path) { if escapeColon { escapeColon = false if c == ':' { continue } panic("invalid escape string in path '" + path + "'") } if c == '\\' { escapeColon = true continue } // A wildcard starts with ':' (param) or '*' (catch-all) if c != ':' && c != '*' { continue } // Find end and check for invalid characters valid = true for end, c := range []byte(path[start+1:]) { switch c { case '/': return path[start : start+1+end], start, valid case ':', '*': valid = false } } return path[start:], start, valid } return "", -1, false } func (n *node) insertChild(path string, fullPath string, handlers HandlersChain) { for { // Find prefix until first wildcard wildcard, i, valid := findWildcard(path) if i < 0 { // No wildcard found break } // The wildcard name must only contain one ':' or '*' character if !valid { panic("only one wildcard per path segment is allowed, has: '" + wildcard + "' in path '" + fullPath + "'") } // check if the wildcard has a name if len(wildcard) < 2 { panic("wildcards must be named with a non-empty name in path '" + fullPath + "'") } if wildcard[0] == ':' { // param if i > 0 { // Insert prefix before the current wildcard n.path = path[:i] path = path[i:] } child := &node{ nType: param, path: wildcard, fullPath: fullPath, } n.addChild(child) n.wildChild = true n = child n.priority++ // if the path doesn't end with the wildcard, then there // will be another subpath starting with '/' if len(wildcard) < len(path) { path = path[len(wildcard):] child := &node{ priority: 1, fullPath: fullPath, } n.addChild(child) n = child continue } // Otherwise we're done. Insert the handle in the new leaf n.handlers = handlers return } // catchAll if i+len(wildcard) != len(path) { panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'") } if len(n.path) > 0 && n.path[len(n.path)-1] == '/' { pathSeg := "" if len(n.children) != 0 { pathSeg, _, _ = strings.Cut(n.children[0].path, "/") } panic("catch-all wildcard '" + path + "' in new path '" + fullPath + "' conflicts with existing path segment '" + pathSeg + "' in existing prefix '" + n.path + pathSeg + "'") } // currently fixed width 1 for '/' i-- if i < 0 || path[i] != '/' { panic("no / before catch-all in path '" + fullPath + "'") } n.path = path[:i] // First node: catchAll node with empty path child := &node{ wildChild: true, nType: catchAll, fullPath: fullPath, } n.addChild(child) n.indices = "/" n = child n.priority++ // second node: node holding the variable child = &node{ path: path[i:], nType: catchAll, handlers: handlers, priority: 1, fullPath: fullPath, } n.children = []*node{child} return } // If no wildcard was found, simply insert the path and handle n.path = path n.handlers = handlers n.fullPath = fullPath } // nodeValue holds return values of (*Node).getValue method type nodeValue struct { handlers HandlersChain params *Params tsr bool fullPath string } type skippedNode struct { path string node *node paramsCount int16 } // Returns the handle registered with the given path (key). The values of // wildcards are saved to a map. // If no handle can be found, a TSR (trailing slash redirect) recommendation is // made if a handle exists with an extra (without the) trailing slash for the // given path. func (n *node) getValue(path string, params *Params, skippedNodes *[]skippedNode, unescape bool) (value nodeValue) { var globalParamsCount int16 walk: // Outer loop for walking the tree for { prefix := n.path if len(path) > len(prefix) { if path[:len(prefix)] == prefix { path = path[len(prefix):] // Try all the non-wildcard children first by matching the indices idxc := path[0] for i, c := range []byte(n.indices) { if c == idxc { // strings.HasPrefix(n.children[len(n.children)-1].path, ":") == n.wildChild if n.wildChild { index := len(*skippedNodes) *skippedNodes = (*skippedNodes)[:index+1] (*skippedNodes)[index] = skippedNode{ path: prefix + path, node: &node{ path: n.path, wildChild: n.wildChild, nType: n.nType, priority: n.priority, children: n.children, handlers: n.handlers, fullPath: n.fullPath, }, paramsCount: globalParamsCount, } } n = n.children[i] continue walk } } if !n.wildChild { // If the path at the end of the loop is not equal to '/' and the current node has no child nodes // the current node needs to roll back to last valid skippedNode if path != "/" { for length := len(*skippedNodes); length > 0; length-- { skippedNode := (*skippedNodes)[length-1] *skippedNodes = (*skippedNodes)[:length-1] if strings.HasSuffix(skippedNode.path, path) { path = skippedNode.path n = skippedNode.node if value.params != nil { *value.params = (*value.params)[:skippedNode.paramsCount] } globalParamsCount = skippedNode.paramsCount continue walk } } } // Nothing found. // We can recommend to redirect to the same URL without a // trailing slash if a leaf exists for that path. value.tsr = path == "/" && n.handlers != nil return value } // Handle wildcard child, which is always at the end of the array n = n.children[len(n.children)-1] globalParamsCount++ switch n.nType { case param: // fix truncate the parameter // tree_test.go line: 204 // Find param end (either '/' or path end) end := 0 for end < len(path) && path[end] != '/' { end++ } // Save param value if params != nil { // Preallocate capacity if necessary if cap(*params) < int(globalParamsCount) { newParams := make(Params, len(*params), globalParamsCount) copy(newParams, *params) *params = newParams } if value.params == nil { value.params = params } // Expand slice within preallocated capacity i := len(*value.params) *value.params = (*value.params)[:i+1] val := path[:end] if unescape { if v, err := url.QueryUnescape(val); err == nil { val = v } } (*value.params)[i] = Param{ Key: n.path[1:], Value: val, } } // we need to go deeper! if end < len(path) { if len(n.children) > 0 { path = path[end:] n = n.children[0] continue walk } // ... but we can't value.tsr = len(path) == end+1 return value } if value.handlers = n.handlers; value.handlers != nil { value.fullPath = n.fullPath return value } if len(n.children) == 1 { // No handle found. Check if a handle for this path + a // trailing slash exists for TSR recommendation n = n.children[0] value.tsr = (n.path == "/" && n.handlers != nil) || (n.path == "" && n.indices == "/") } return value case catchAll: // Save param value if params != nil { // Preallocate capacity if necessary if cap(*params) < int(globalParamsCount) { newParams := make(Params, len(*params), globalParamsCount) copy(newParams, *params) *params = newParams } if value.params == nil { value.params = params } // Expand slice within preallocated capacity i := len(*value.params) *value.params = (*value.params)[:i+1] val := path if unescape { if v, err := url.QueryUnescape(path); err == nil { val = v } } (*value.params)[i] = Param{ Key: n.path[2:], Value: val, } } value.handlers = n.handlers value.fullPath = n.fullPath return value default: panic("invalid node type") } } } if path == prefix { // If the current path does not equal '/' and the node does not have a registered handle and the most recently matched node has a child node // the current node needs to roll back to last valid skippedNode if n.handlers == nil && path != "/" { for length := len(*skippedNodes); length > 0; length-- { skippedNode := (*skippedNodes)[length-1] *skippedNodes = (*skippedNodes)[:length-1] if strings.HasSuffix(skippedNode.path, path) { path = skippedNode.path n = skippedNode.node if value.params != nil { *value.params = (*value.params)[:skippedNode.paramsCount] } globalParamsCount = skippedNode.paramsCount continue walk } } // n = latestNode.children[len(latestNode.children)-1] } // We should have reached the node containing the handle. // Check if this node has a handle registered. if value.handlers = n.handlers; value.handlers != nil { value.fullPath = n.fullPath return value } // If there is no handle for this route, but this route has a // wildcard child, there must be a handle for this path with an // additional trailing slash if path == "/" && n.wildChild && n.nType != root { value.tsr = true return value } if path == "/" && n.nType == static { value.tsr = true return value } // No handle found. Check if a handle for this path + a // trailing slash exists for trailing slash recommendation for i, c := range []byte(n.indices) { if c == '/' { n = n.children[i] value.tsr = (len(n.path) == 1 && n.handlers != nil) || (n.nType == catchAll && n.children[0].handlers != nil) return value } } return value } // Nothing found. We can recommend to redirect to the same URL with an // extra trailing slash if a leaf exists for that path value.tsr = path == "/" || (len(prefix) == len(path)+1 && prefix[len(path)] == '/' && path == prefix[:len(prefix)-1] && n.handlers != nil) // roll back to last valid skippedNode if !value.tsr && path != "/" { for length := len(*skippedNodes); length > 0; length-- { skippedNode := (*skippedNodes)[length-1] *skippedNodes = (*skippedNodes)[:length-1] if strings.HasSuffix(skippedNode.path, path) { path = skippedNode.path n = skippedNode.node if value.params != nil { *value.params = (*value.params)[:skippedNode.paramsCount] } globalParamsCount = skippedNode.paramsCount continue walk } } } return value } } // Makes a case-insensitive lookup of the given path and tries to find a handler. // It can optionally also fix trailing slashes. // It returns the case-corrected path and a bool indicating whether the lookup // was successful. func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) ([]byte, bool) { const stackBufSize = 128 // Use a static sized buffer on the stack in the common case. // If the path is too long, allocate a buffer on the heap instead. buf := make([]byte, 0, stackBufSize) if length := len(path) + 1; length > stackBufSize { buf = make([]byte, 0, length) } ciPath := n.findCaseInsensitivePathRec( path, buf, // Preallocate enough memory for new path [4]byte{}, // Empty rune buffer fixTrailingSlash, ) return ciPath, ciPath != nil } // Shift bytes in array by n bytes left func shiftNRuneBytes(rb [4]byte, n int) [4]byte { switch n { case 0: return rb case 1: return [4]byte{rb[1], rb[2], rb[3], 0} case 2: return [4]byte{rb[2], rb[3]} case 3: return [4]byte{rb[3]} default: return [4]byte{} } } // Recursive case-insensitive lookup function used by n.findCaseInsensitivePath func (n *node) findCaseInsensitivePathRec(path string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) []byte { npLen := len(n.path) walk: // Outer loop for walking the tree for len(path) >= npLen && (npLen == 0 || strings.EqualFold(path[1:npLen], n.path[1:])) { // Add common prefix to result oldPath := path path = path[npLen:] ciPath = append(ciPath, n.path...) if len(path) == 0 { // We should have reached the node containing the handle. // Check if this node has a handle registered. if n.handlers != nil { return ciPath } // No handle found. // Try to fix the path by adding a trailing slash if fixTrailingSlash { for i, c := range []byte(n.indices) { if c == '/' { n = n.children[i] if (len(n.path) == 1 && n.handlers != nil) || (n.nType == catchAll && n.children[0].handlers != nil) { return append(ciPath, '/') } return nil } } } return nil } // If this node does not have a wildcard (param or catchAll) child, // we can just look up the next child node and continue to walk down // the tree if !n.wildChild { // Skip rune bytes already processed rb = shiftNRuneBytes(rb, npLen) if rb[0] != 0 { // Old rune not finished idxc := rb[0] for i, c := range []byte(n.indices) { if c == idxc { // continue with child node n = n.children[i] npLen = len(n.path) continue walk } } } else { // Process a new rune var rv rune // Find rune start. // Runes are up to 4 byte long, // -4 would definitely be another rune. var off int for max_ := min(npLen, 3); off < max_; off++ { if i := npLen - off; utf8.RuneStart(oldPath[i]) { // read rune from cached path rv, _ = utf8.DecodeRuneInString(oldPath[i:]) break } } // Calculate lowercase bytes of current rune lo := unicode.ToLower(rv) utf8.EncodeRune(rb[:], lo) // Skip already processed bytes rb = shiftNRuneBytes(rb, off) idxc := rb[0] for i, c := range []byte(n.indices) { // Lowercase matches if c == idxc { // must use a recursive approach since both the // uppercase byte and the lowercase byte might exist // as an index if out := n.children[i].findCaseInsensitivePathRec( path, ciPath, rb, fixTrailingSlash, ); out != nil { return out } break } } // If we found no match, the same for the uppercase rune, // if it differs if up := unicode.ToUpper(rv); up != lo { utf8.EncodeRune(rb[:], up) rb = shiftNRuneBytes(rb, off) idxc := rb[0] for i, c := range []byte(n.indices) { // Uppercase matches if c == idxc { // Continue with child node n = n.children[i] npLen = len(n.path) continue walk } } } } // Nothing found. We can recommend to redirect to the same URL // without a trailing slash if a leaf exists for that path if fixTrailingSlash && path == "/" && n.handlers != nil { return ciPath } return nil } n = n.children[0] switch n.nType { case param: // Find param end (either '/' or path end) end := 0 for end < len(path) && path[end] != '/' { end++ } // Add param value to case insensitive path ciPath = append(ciPath, path[:end]...) // We need to go deeper! if end < len(path) { if len(n.children) > 0 { // Continue with child node n = n.children[0] npLen = len(n.path) path = path[end:] continue } // ... but we can't if fixTrailingSlash && len(path) == end+1 { return ciPath } return nil } if n.handlers != nil { return ciPath } if fixTrailingSlash && len(n.children) == 1 { // No handle found. Check if a handle for this path + a // trailing slash exists n = n.children[0] if n.path == "/" && n.handlers != nil { return append(ciPath, '/') } } return nil case catchAll: return append(ciPath, path...) default: panic("invalid node type") } } // Nothing found. // Try to fix the path by adding / removing a trailing slash if fixTrailingSlash { if path == "/" { return ciPath } if len(path)+1 == npLen && n.path[len(path)] == '/' && strings.EqualFold(path[1:], n.path[1:len(path)]) && n.handlers != nil { return append(ciPath, n.path...) } } return nil }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/gin_integration_test.go
gin_integration_test.go
// Copyright 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 ( "bufio" "crypto/tls" "fmt" "html/template" "io" "net" "net/http" "net/http/httptest" "os" "path/filepath" "runtime" "strings" "sync" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // params[0]=url example:http://127.0.0.1:8080/index (cannot be empty) // params[1]=response status (custom compare status) default:"200 OK" // params[2]=response body (custom compare content) default:"it worked" func testRequest(t *testing.T, params ...string) { if len(params) == 0 { t.Fatal("url cannot be empty") } tr := &http.Transport{ TLSClientConfig: &tls.Config{ 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 = params[1] } responseBody := "it worked" if len(params) > 2 && params[2] != "" { responseBody = params[2] } assert.Equal(t, responseStatus, resp.Status, "should get a "+responseStatus) if 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 *Context) { 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 successfully") require.Error(t, router.Run(":8080")) testRequest(t, "http://localhost:8080/example") } func TestBadTrustedCIDRs(t *testing.T) { router := New() require.Error(t, router.SetTrustedProxies([]string{"hello/world"})) } /* legacy tests func TestBadTrustedCIDRsForRun(t *testing.T) { os.Setenv("PORT", "") router := New() router.TrustedProxies = []string{"hello/world"} require.Error(t, router.Run(":8080")) } func TestBadTrustedCIDRsForRunUnix(t *testing.T) { router := New() router.TrustedProxies = []string{"hello/world"} unixTestSocket := filepath.Join(os.TempDir(), "unix_unit_test") defer os.Remove(unixTestSocket) go func() { router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) require.Error(t, router.RunUnix(unixTestSocket)) }() // have to wait for the goroutine to start and run the server // otherwise the main thread will complete time.Sleep(5 * time.Millisecond) } func TestBadTrustedCIDRsForRunFd(t *testing.T) { router := New() router.TrustedProxies = []string{"hello/world"} addr, err := net.ResolveTCPAddr("tcp", "localhost:0") require.NoError(t, err) listener, err := net.ListenTCP("tcp", addr) require.NoError(t, err) socketFile, err := listener.File() require.NoError(t, err) go func() { router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) require.Error(t, router.RunFd(int(socketFile.Fd()))) }() // have to wait for the goroutine to start and run the server // otherwise the main thread will complete time.Sleep(5 * time.Millisecond) } func TestBadTrustedCIDRsForRunListener(t *testing.T) { router := New() router.TrustedProxies = []string{"hello/world"} addr, err := net.ResolveTCPAddr("tcp", "localhost:0") require.NoError(t, err) listener, err := net.ListenTCP("tcp", addr) require.NoError(t, err) go func() { router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) require.Error(t, router.RunListener(listener)) }() // have to wait for the goroutine to start and run the server // otherwise the main thread will complete time.Sleep(5 * time.Millisecond) } func TestBadTrustedCIDRsForRunTLS(t *testing.T) { os.Setenv("PORT", "") router := New() router.TrustedProxies = []string{"hello/world"} require.Error(t, router.RunTLS(":8080", "./testdata/certificate/cert.pem", "./testdata/certificate/key.pem")) } */ func TestRunTLS(t *testing.T) { router := New() go func() { router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) assert.NoError(t, router.RunTLS(":8443", "./testdata/certificate/cert.pem", "./testdata/certificate/key.pem")) }() // have to wait for the goroutine to start and run the server // otherwise the main thread will complete time.Sleep(5 * time.Millisecond) require.Error(t, router.RunTLS(":8443", "./testdata/certificate/cert.pem", "./testdata/certificate/key.pem")) testRequest(t, "https://localhost:8443/example") } func TestPusher(t *testing.T) { html := template.Must(template.New("https").Parse(` <html> <head> <title>Https Test</title> <script src="/assets/app.js"></script> </head> <body> <h1 style="color:red;">Welcome, Ginner!</h1> </body> </html> `)) router := New() router.Static("./assets", "./assets") router.SetHTMLTemplate(html) go func() { router.GET("/pusher", func(c *Context) { if pusher := c.Writer.Pusher(); pusher != nil { err := pusher.Push("/assets/app.js", nil) assert.NoError(t, err) } c.String(http.StatusOK, "it worked") }) assert.NoError(t, router.RunTLS(":8449", "./testdata/certificate/cert.pem", "./testdata/certificate/key.pem")) }() // have to wait for the goroutine to start and run the server // otherwise the main thread will complete time.Sleep(5 * time.Millisecond) require.Error(t, router.RunTLS(":8449", "./testdata/certificate/cert.pem", "./testdata/certificate/key.pem")) testRequest(t, "https://localhost:8449/pusher") } func TestRunEmptyWithEnv(t *testing.T) { os.Setenv("PORT", "3123") router := New() go func() { router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) assert.NoError(t, router.Run()) }() // Wait for server to be ready with exponential backoff err := waitForServerReady("http://localhost:3123/example", 10) require.NoError(t, err, "server should start successfully") require.Error(t, router.Run(":3123")) testRequest(t, "http://localhost:3123/example") } func TestRunTooMuchParams(t *testing.T) { router := New() assert.Panics(t, func() { require.NoError(t, router.Run("2", "2")) }) } func TestRunWithPort(t *testing.T) { router := New() go func() { router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) assert.NoError(t, router.Run(":5150")) }() // Wait for server to be ready with exponential backoff err := waitForServerReady("http://localhost:5150/example", 10) require.NoError(t, err, "server should start successfully") require.Error(t, router.Run(":5150")) testRequest(t, "http://localhost:5150/example") } func TestUnixSocket(t *testing.T) { router := New() unixTestSocket := filepath.Join(os.TempDir(), "unix_unit_test") defer os.Remove(unixTestSocket) go func() { router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) assert.NoError(t, router.RunUnix(unixTestSocket)) }() // have to wait for the goroutine to start and run the server // otherwise the main thread will complete time.Sleep(5 * time.Millisecond) c, err := net.Dial("unix", unixTestSocket) require.NoError(t, err) fmt.Fprint(c, "GET /example HTTP/1.0\r\n\r\n") scanner := bufio.NewScanner(c) var responseBuilder strings.Builder for scanner.Scan() { responseBuilder.WriteString(scanner.Text()) } response := responseBuilder.String() assert.Contains(t, response, "HTTP/1.0 200", "should get a 200") assert.Contains(t, response, "it worked", "resp body should match") } func TestBadUnixSocket(t *testing.T) { router := New() require.Error(t, router.RunUnix("#/tmp/unix_unit_test")) } func TestRunQUIC(t *testing.T) { router := New() go func() { router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) assert.NoError(t, router.RunQUIC(":8443", "./testdata/certificate/cert.pem", "./testdata/certificate/key.pem")) }() // have to wait for the goroutine to start and run the server // otherwise the main thread will complete time.Sleep(5 * time.Millisecond) require.Error(t, router.RunQUIC(":8443", "./testdata/certificate/cert.pem", "./testdata/certificate/key.pem")) testRequest(t, "https://localhost:8443/example") } func TestFileDescriptor(t *testing.T) { router := New() addr, err := net.ResolveTCPAddr("tcp", "localhost:0") require.NoError(t, err) listener, err := net.ListenTCP("tcp", addr) require.NoError(t, err) socketFile, err := listener.File() if isWindows() { // not supported by windows, it is unimplemented now require.Error(t, err) } else { require.NoError(t, err) } if socketFile == nil { return } go func() { router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) assert.NoError(t, router.RunFd(int(socketFile.Fd()))) }() // have to wait for the goroutine to start and run the server // otherwise the main thread will complete time.Sleep(5 * time.Millisecond) c, err := net.Dial("tcp", listener.Addr().String()) require.NoError(t, err) fmt.Fprintf(c, "GET /example HTTP/1.0\r\n\r\n") scanner := bufio.NewScanner(c) var responseBuilder strings.Builder for scanner.Scan() { responseBuilder.WriteString(scanner.Text()) } response := responseBuilder.String() assert.Contains(t, response, "HTTP/1.0 200", "should get a 200") assert.Contains(t, response, "it worked", "resp body should match") } func TestBadFileDescriptor(t *testing.T) { router := New() require.Error(t, router.RunFd(0)) } func TestListener(t *testing.T) { router := New() addr, err := net.ResolveTCPAddr("tcp", "localhost:0") require.NoError(t, err) listener, err := net.ListenTCP("tcp", addr) require.NoError(t, err) go func() { router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) assert.NoError(t, router.RunListener(listener)) }() // have to wait for the goroutine to start and run the server // otherwise the main thread will complete time.Sleep(5 * time.Millisecond) c, err := net.Dial("tcp", listener.Addr().String()) require.NoError(t, err) fmt.Fprintf(c, "GET /example HTTP/1.0\r\n\r\n") scanner := bufio.NewScanner(c) var responseBuilder strings.Builder for scanner.Scan() { responseBuilder.WriteString(scanner.Text()) } response := responseBuilder.String() assert.Contains(t, response, "HTTP/1.0 200", "should get a 200") assert.Contains(t, response, "it worked", "resp body should match") } func TestBadListener(t *testing.T) { router := New() addr, err := net.ResolveTCPAddr("tcp", "localhost:10086") require.NoError(t, err) listener, err := net.ListenTCP("tcp", addr) require.NoError(t, err) listener.Close() require.Error(t, router.RunListener(listener)) } func TestWithHttptestWithAutoSelectedPort(t *testing.T) { router := New() router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) ts := httptest.NewServer(router) defer ts.Close() testRequest(t, ts.URL+"/example") } func TestConcurrentHandleContext(t *testing.T) { router := New() router.GET("/", func(c *Context) { c.Request.URL.Path = "/example" router.HandleContext(c) }) router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) var wg sync.WaitGroup iterations := 200 wg.Add(iterations) for i := 0; i < iterations; i++ { go func() { req, err := http.NewRequest(http.MethodGet, "/", nil) assert.NoError(t, err) w := httptest.NewRecorder() router.ServeHTTP(w, req) assert.Equal(t, "it worked", w.Body.String(), "resp body should match") assert.Equal(t, 200, w.Code, "should get a 200") wg.Done() }() } wg.Wait() } // func TestWithHttptestWithSpecifiedPort(t *testing.T) { // router := New() // router.GET("/example", func(c *Context) { c.String(http.StatusOK, "it worked") }) // l, _ := net.Listen("tcp", ":8033") // ts := httptest.Server{ // Listener: l, // Config: &http.Server{Handler: router}, // } // ts.Start() // defer ts.Close() // testRequest(t, "http://localhost:8033/example") // } func TestTreeRunDynamicRouting(t *testing.T) { router := New() router.GET("/aa/*xx", func(c *Context) { c.String(http.StatusOK, "/aa/*xx") }) router.GET("/ab/*xx", func(c *Context) { c.String(http.StatusOK, "/ab/*xx") }) router.GET("/", func(c *Context) { c.String(http.StatusOK, "home") }) router.GET("/:cc", func(c *Context) { c.String(http.StatusOK, "/:cc") }) router.GET("/c1/:dd/e", func(c *Context) { c.String(http.StatusOK, "/c1/:dd/e") }) router.GET("/c1/:dd/e1", func(c *Context) { c.String(http.StatusOK, "/c1/:dd/e1") }) router.GET("/c1/:dd/f1", func(c *Context) { c.String(http.StatusOK, "/c1/:dd/f1") }) router.GET("/c1/:dd/f2", func(c *Context) { c.String(http.StatusOK, "/c1/:dd/f2") }) router.GET("/:cc/cc", func(c *Context) { c.String(http.StatusOK, "/:cc/cc") }) router.GET("/:cc/:dd/ee", func(c *Context) { c.String(http.StatusOK, "/:cc/:dd/ee") }) router.GET("/:cc/:dd/f", func(c *Context) { c.String(http.StatusOK, "/:cc/:dd/f") }) router.GET("/:cc/:dd/:ee/ff", func(c *Context) { c.String(http.StatusOK, "/:cc/:dd/:ee/ff") }) router.GET("/:cc/:dd/:ee/:ff/gg", func(c *Context) { c.String(http.StatusOK, "/:cc/:dd/:ee/:ff/gg") }) router.GET("/:cc/:dd/:ee/:ff/:gg/hh", func(c *Context) { c.String(http.StatusOK, "/:cc/:dd/:ee/:ff/:gg/hh") }) router.GET("/get/test/abc/", func(c *Context) { c.String(http.StatusOK, "/get/test/abc/") }) router.GET("/get/:param/abc/", func(c *Context) { c.String(http.StatusOK, "/get/:param/abc/") }) router.GET("/something/:paramname/thirdthing", func(c *Context) { c.String(http.StatusOK, "/something/:paramname/thirdthing") }) router.GET("/something/secondthing/test", func(c *Context) { c.String(http.StatusOK, "/something/secondthing/test") }) router.GET("/get/abc", func(c *Context) { c.String(http.StatusOK, "/get/abc") }) router.GET("/get/:param", func(c *Context) { c.String(http.StatusOK, "/get/:param") }) router.GET("/get/abc/123abc", func(c *Context) { c.String(http.StatusOK, "/get/abc/123abc") }) router.GET("/get/abc/:param", func(c *Context) { c.String(http.StatusOK, "/get/abc/:param") }) router.GET("/get/abc/123abc/xxx8", func(c *Context) { c.String(http.StatusOK, "/get/abc/123abc/xxx8") }) router.GET("/get/abc/123abc/:param", func(c *Context) { c.String(http.StatusOK, "/get/abc/123abc/:param") }) router.GET("/get/abc/123abc/xxx8/1234", func(c *Context) { c.String(http.StatusOK, "/get/abc/123abc/xxx8/1234") }) router.GET("/get/abc/123abc/xxx8/:param", func(c *Context) { c.String(http.StatusOK, "/get/abc/123abc/xxx8/:param") }) router.GET("/get/abc/123abc/xxx8/1234/ffas", func(c *Context) { c.String(http.StatusOK, "/get/abc/123abc/xxx8/1234/ffas") }) router.GET("/get/abc/123abc/xxx8/1234/:param", func(c *Context) { c.String(http.StatusOK, "/get/abc/123abc/xxx8/1234/:param") }) router.GET("/get/abc/123abc/xxx8/1234/kkdd/12c", func(c *Context) { c.String(http.StatusOK, "/get/abc/123abc/xxx8/1234/kkdd/12c") }) router.GET("/get/abc/123abc/xxx8/1234/kkdd/:param", func(c *Context) { c.String(http.StatusOK, "/get/abc/123abc/xxx8/1234/kkdd/:param") }) router.GET("/get/abc/:param/test", func(c *Context) { c.String(http.StatusOK, "/get/abc/:param/test") }) router.GET("/get/abc/123abd/:param", func(c *Context) { c.String(http.StatusOK, "/get/abc/123abd/:param") }) router.GET("/get/abc/123abddd/:param", func(c *Context) { c.String(http.StatusOK, "/get/abc/123abddd/:param") }) router.GET("/get/abc/123/:param", func(c *Context) { c.String(http.StatusOK, "/get/abc/123/:param") }) router.GET("/get/abc/123abg/:param", func(c *Context) { c.String(http.StatusOK, "/get/abc/123abg/:param") }) router.GET("/get/abc/123abf/:param", func(c *Context) { c.String(http.StatusOK, "/get/abc/123abf/:param") }) router.GET("/get/abc/123abfff/:param", func(c *Context) { c.String(http.StatusOK, "/get/abc/123abfff/:param") }) ts := httptest.NewServer(router) defer ts.Close() testRequest(t, ts.URL+"/", "", "home") testRequest(t, ts.URL+"/aa/aa", "", "/aa/*xx") testRequest(t, ts.URL+"/ab/ab", "", "/ab/*xx") testRequest(t, ts.URL+"/all", "", "/:cc") testRequest(t, ts.URL+"/all/cc", "", "/:cc/cc") testRequest(t, ts.URL+"/a/cc", "", "/:cc/cc") testRequest(t, ts.URL+"/c1/d/e", "", "/c1/:dd/e") testRequest(t, ts.URL+"/c1/d/e1", "", "/c1/:dd/e1") testRequest(t, ts.URL+"/c1/d/ee", "", "/:cc/:dd/ee") testRequest(t, ts.URL+"/c1/d/f", "", "/:cc/:dd/f") testRequest(t, ts.URL+"/c/d/ee", "", "/:cc/:dd/ee") testRequest(t, ts.URL+"/c/d/e/ff", "", "/:cc/:dd/:ee/ff") testRequest(t, ts.URL+"/c/d/e/f/gg", "", "/:cc/:dd/:ee/:ff/gg") testRequest(t, ts.URL+"/c/d/e/f/g/hh", "", "/:cc/:dd/:ee/:ff/:gg/hh") testRequest(t, ts.URL+"/cc/dd/ee/ff/gg/hh", "", "/:cc/:dd/:ee/:ff/:gg/hh") testRequest(t, ts.URL+"/a", "", "/:cc") testRequest(t, ts.URL+"/d", "", "/:cc") testRequest(t, ts.URL+"/ad", "", "/:cc") testRequest(t, ts.URL+"/dd", "", "/:cc") testRequest(t, ts.URL+"/aa", "", "/:cc") testRequest(t, ts.URL+"/aaa", "", "/:cc") testRequest(t, ts.URL+"/aaa/cc", "", "/:cc/cc") testRequest(t, ts.URL+"/ab", "", "/:cc") testRequest(t, ts.URL+"/abb", "", "/:cc") testRequest(t, ts.URL+"/abb/cc", "", "/:cc/cc") testRequest(t, ts.URL+"/dddaa", "", "/:cc") testRequest(t, ts.URL+"/allxxxx", "", "/:cc") testRequest(t, ts.URL+"/alldd", "", "/:cc") testRequest(t, ts.URL+"/cc/cc", "", "/:cc/cc") testRequest(t, ts.URL+"/ccc/cc", "", "/:cc/cc") testRequest(t, ts.URL+"/deedwjfs/cc", "", "/:cc/cc") testRequest(t, ts.URL+"/acllcc/cc", "", "/:cc/cc") testRequest(t, ts.URL+"/get/test/abc/", "", "/get/test/abc/") testRequest(t, ts.URL+"/get/testaa/abc/", "", "/get/:param/abc/") testRequest(t, ts.URL+"/get/te/abc/", "", "/get/:param/abc/") testRequest(t, ts.URL+"/get/xx/abc/", "", "/get/:param/abc/") testRequest(t, ts.URL+"/get/tt/abc/", "", "/get/:param/abc/") testRequest(t, ts.URL+"/get/a/abc/", "", "/get/:param/abc/") testRequest(t, ts.URL+"/get/t/abc/", "", "/get/:param/abc/") testRequest(t, ts.URL+"/get/aa/abc/", "", "/get/:param/abc/") testRequest(t, ts.URL+"/get/abas/abc/", "", "/get/:param/abc/") testRequest(t, ts.URL+"/something/secondthing/test", "", "/something/secondthing/test") testRequest(t, ts.URL+"/something/secondthingaaaa/thirdthing", "", "/something/:paramname/thirdthing") testRequest(t, ts.URL+"/something/abcdad/thirdthing", "", "/something/:paramname/thirdthing") testRequest(t, ts.URL+"/something/se/thirdthing", "", "/something/:paramname/thirdthing") testRequest(t, ts.URL+"/something/s/thirdthing", "", "/something/:paramname/thirdthing") testRequest(t, ts.URL+"/something/secondthing/thirdthing", "", "/something/:paramname/thirdthing") testRequest(t, ts.URL+"/get/abc", "", "/get/abc") testRequest(t, ts.URL+"/get/a", "", "/get/:param") testRequest(t, ts.URL+"/get/abz", "", "/get/:param") testRequest(t, ts.URL+"/get/12a", "", "/get/:param") testRequest(t, ts.URL+"/get/abcd", "", "/get/:param") testRequest(t, ts.URL+"/get/abc/123abc", "", "/get/abc/123abc") testRequest(t, ts.URL+"/get/abc/12", "", "/get/abc/:param") testRequest(t, ts.URL+"/get/abc/123ab", "", "/get/abc/:param") testRequest(t, ts.URL+"/get/abc/xyz", "", "/get/abc/:param") testRequest(t, ts.URL+"/get/abc/123abcddxx", "", "/get/abc/:param") testRequest(t, ts.URL+"/get/abc/123abc/xxx8", "", "/get/abc/123abc/xxx8") testRequest(t, ts.URL+"/get/abc/123abc/x", "", "/get/abc/123abc/:param") testRequest(t, ts.URL+"/get/abc/123abc/xxx", "", "/get/abc/123abc/:param") testRequest(t, ts.URL+"/get/abc/123abc/abc", "", "/get/abc/123abc/:param") testRequest(t, ts.URL+"/get/abc/123abc/xxx8xxas", "", "/get/abc/123abc/:param") testRequest(t, ts.URL+"/get/abc/123abc/xxx8/1234", "", "/get/abc/123abc/xxx8/1234") testRequest(t, ts.URL+"/get/abc/123abc/xxx8/1", "", "/get/abc/123abc/xxx8/:param") testRequest(t, ts.URL+"/get/abc/123abc/xxx8/123", "", "/get/abc/123abc/xxx8/:param") testRequest(t, ts.URL+"/get/abc/123abc/xxx8/78k", "", "/get/abc/123abc/xxx8/:param") testRequest(t, ts.URL+"/get/abc/123abc/xxx8/1234xxxd", "", "/get/abc/123abc/xxx8/:param") testRequest(t, ts.URL+"/get/abc/123abc/xxx8/1234/ffas", "", "/get/abc/123abc/xxx8/1234/ffas") testRequest(t, ts.URL+"/get/abc/123abc/xxx8/1234/f", "", "/get/abc/123abc/xxx8/1234/:param") testRequest(t, ts.URL+"/get/abc/123abc/xxx8/1234/ffa", "", "/get/abc/123abc/xxx8/1234/:param") testRequest(t, ts.URL+"/get/abc/123abc/xxx8/1234/kka", "", "/get/abc/123abc/xxx8/1234/:param") testRequest(t, ts.URL+"/get/abc/123abc/xxx8/1234/ffas321", "", "/get/abc/123abc/xxx8/1234/:param") testRequest(t, ts.URL+"/get/abc/123abc/xxx8/1234/kkdd/12c", "", "/get/abc/123abc/xxx8/1234/kkdd/12c") testRequest(t, ts.URL+"/get/abc/123abc/xxx8/1234/kkdd/1", "", "/get/abc/123abc/xxx8/1234/kkdd/:param") testRequest(t, ts.URL+"/get/abc/123abc/xxx8/1234/kkdd/12", "", "/get/abc/123abc/xxx8/1234/kkdd/:param") testRequest(t, ts.URL+"/get/abc/123abc/xxx8/1234/kkdd/12b", "", "/get/abc/123abc/xxx8/1234/kkdd/:param") testRequest(t, ts.URL+"/get/abc/123abc/xxx8/1234/kkdd/34", "", "/get/abc/123abc/xxx8/1234/kkdd/:param") testRequest(t, ts.URL+"/get/abc/123abc/xxx8/1234/kkdd/12c2e3", "", "/get/abc/123abc/xxx8/1234/kkdd/:param") testRequest(t, ts.URL+"/get/abc/12/test", "", "/get/abc/:param/test") testRequest(t, ts.URL+"/get/abc/123abdd/test", "", "/get/abc/:param/test") testRequest(t, ts.URL+"/get/abc/123abdddf/test", "", "/get/abc/:param/test") testRequest(t, ts.URL+"/get/abc/123ab/test", "", "/get/abc/:param/test") testRequest(t, ts.URL+"/get/abc/123abgg/test", "", "/get/abc/:param/test") testRequest(t, ts.URL+"/get/abc/123abff/test", "", "/get/abc/:param/test") testRequest(t, ts.URL+"/get/abc/123abffff/test", "", "/get/abc/:param/test") testRequest(t, ts.URL+"/get/abc/123abd/test", "", "/get/abc/123abd/:param") testRequest(t, ts.URL+"/get/abc/123abddd/test", "", "/get/abc/123abddd/:param") testRequest(t, ts.URL+"/get/abc/123/test22", "", "/get/abc/123/:param") testRequest(t, ts.URL+"/get/abc/123abg/test", "", "/get/abc/123abg/:param") testRequest(t, ts.URL+"/get/abc/123abf/testss", "", "/get/abc/123abf/:param") testRequest(t, ts.URL+"/get/abc/123abfff/te", "", "/get/abc/123abfff/:param") // 404 not found testRequest(t, ts.URL+"/c/d/e", "404 Not Found") testRequest(t, ts.URL+"/c/d/e1", "404 Not Found") testRequest(t, ts.URL+"/c/d/eee", "404 Not Found") testRequest(t, ts.URL+"/c1/d/eee", "404 Not Found") testRequest(t, ts.URL+"/c1/d/e2", "404 Not Found") testRequest(t, ts.URL+"/cc/dd/ee/ff/gg/hh1", "404 Not Found") testRequest(t, ts.URL+"/a/dd", "404 Not Found") testRequest(t, ts.URL+"/addr/dd/aa", "404 Not Found") testRequest(t, ts.URL+"/something/secondthing/121", "404 Not Found") } func isWindows() bool { return runtime.GOOS == "windows" } func TestEscapedColon(t *testing.T) { router := New() f := func(u string) { router.GET(u, func(c *Context) { c.String(http.StatusOK, u) }) } f("/r/r\\:r") f("/r/r:r") f("/r/r/:r") f("/r/r/\\:r") f("/r/r/r\\:r") assert.Panics(t, func() { f("\\foo:") }) router.updateRouteTrees() ts := httptest.NewServer(router) defer ts.Close() testRequest(t, ts.URL+"/r/r123", "", "/r/r:r") testRequest(t, ts.URL+"/r/r:r", "", "/r/r\\:r") testRequest(t, ts.URL+"/r/r/r123", "", "/r/r/:r") testRequest(t, ts.URL+"/r/r/:r", "", "/r/r/\\:r") testRequest(t, ts.URL+"/r/r/r:r", "", "/r/r/r\\:r") }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/deprecated_test.go
deprecated_test.go
// 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 gin import ( "bytes" "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin/binding" "github.com/stretchr/testify/assert" ) func TestBindWith(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Request, _ = http.NewRequest(http.MethodPost, "/?foo=bar&bar=foo", bytes.NewBufferString("foo=unused")) var obj struct { Foo string `form:"foo"` Bar string `form:"bar"` } captureOutput(t, func() { assert.NoError(t, c.BindWith(&obj, binding.Form)) }) assert.Equal(t, "foo", obj.Bar) assert.Equal(t, "bar", obj.Foo) assert.Equal(t, 0, w.Body.Len()) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/routergroup_test.go
routergroup_test.go
// 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 gin import ( "net/http" "testing" "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.BasePath()) assert.Equal(t, router, group.engine) group2 := group.Group("manu") group2.Use(func(c *Context) {}, func(c *Context) {}) assert.Len(t, group2.Handlers, 4) assert.Equal(t, "/hola/manu", group2.BasePath()) assert.Equal(t, router, group2.engine) } func TestRouterGroupBasicHandle(t *testing.T) { performRequestInGroup(t, http.MethodGet) performRequestInGroup(t, http.MethodPost) performRequestInGroup(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) { router := New() v1 := router.Group("v1", func(c *Context) {}) assert.Equal(t, "/v1", v1.BasePath()) login := v1.Group("/login/", func(c *Context) {}, func(c *Context) {}) assert.Equal(t, "/v1/login/", login.BasePath()) handler := func(c *Context) { c.String(http.StatusBadRequest, "the method was %s and index %d", c.Request.Method, c.index) } switch method { case http.MethodGet: v1.GET("/test", handler) login.GET("/test", handler) case http.MethodPost: v1.POST("/test", handler) login.POST("/test", handler) case http.MethodPut: v1.PUT("/test", handler) login.PUT("/test", handler) case http.MethodPatch: v1.PATCH("/test", handler) login.PATCH("/test", handler) case http.MethodDelete: v1.DELETE("/test", handler) login.DELETE("/test", handler) case http.MethodHead: v1.HEAD("/test", handler) login.HEAD("/test", handler) case http.MethodOptions: v1.OPTIONS("/test", handler) login.OPTIONS("/test", handler) default: panic("unknown method") } w := PerformRequest(router, method, "/v1/login/test") assert.Equal(t, http.StatusBadRequest, w.Code) assert.Equal(t, "the method was "+method+" and index 3", w.Body.String()) w = PerformRequest(router, method, "/v1/test") assert.Equal(t, http.StatusBadRequest, w.Code) assert.Equal(t, "the method was "+method+" and index 1", w.Body.String()) } func TestRouterGroupInvalidStatic(t *testing.T) { router := New() assert.Panics(t, func() { router.Static("/path/:param", "/") }) assert.Panics(t, func() { router.Static("/path/*param", "/") }) } func TestRouterGroupInvalidStaticFile(t *testing.T) { router := New() assert.Panics(t, func() { router.StaticFile("/path/:param", "favicon.ico") }) assert.Panics(t, func() { router.StaticFile("/path/*param", "favicon.ico") }) } func TestRouterGroupInvalidStaticFileFS(t *testing.T) { router := New() assert.Panics(t, func() { router.StaticFileFS("/path/:param", "favicon.ico", Dir(".", false)) }) assert.Panics(t, func() { router.StaticFileFS("/path/*param", "favicon.ico", Dir(".", false)) }) } func TestRouterGroupTooManyHandlers(t *testing.T) { const ( panicValue = "too many handlers" maximumCnt = abortIndex ) router := New() handlers1 := make([]HandlerFunc, maximumCnt-1) router.Use(handlers1...) handlers2 := make([]HandlerFunc, maximumCnt+1) assert.PanicsWithValue(t, panicValue, func() { router.Use(handlers2...) }) assert.PanicsWithValue(t, panicValue, func() { router.GET("/", handlers2...) }) } func TestRouterGroupBadMethod(t *testing.T) { router := New() assert.Panics(t, func() { router.Handle(http.MethodGet, "/") }) assert.Panics(t, func() { router.Handle(" GET", "/") }) assert.Panics(t, func() { router.Handle("GET ", "/") }) assert.Panics(t, func() { router.Handle("", "/") }) assert.Panics(t, func() { router.Handle("PO ST", "/") }) assert.Panics(t, func() { router.Handle("1GET", "/") }) assert.Panics(t, func() { router.Handle("PATCh", "/") }) } func TestRouterGroupPipeline(t *testing.T) { router := New() testRoutesInterface(t, router) v1 := router.Group("/v1") testRoutesInterface(t, v1) } func testRoutesInterface(t *testing.T, r IRoutes) { handler := func(c *Context) {} assert.Equal(t, r, r.Use(handler)) assert.Equal(t, r, r.Handle(http.MethodGet, "/handler", handler)) assert.Equal(t, r, r.Any("/any", handler)) assert.Equal(t, r, r.GET("/", handler)) assert.Equal(t, r, r.POST("/", handler)) assert.Equal(t, r, r.DELETE("/", handler)) assert.Equal(t, r, r.PATCH("/", handler)) assert.Equal(t, r, r.PUT("/", handler)) assert.Equal(t, r, r.OPTIONS("/", handler)) assert.Equal(t, r, r.HEAD("/", handler)) assert.Equal(t, r, r.Match([]string{http.MethodPut, http.MethodPatch}, "/match", handler)) assert.Equal(t, r, r.StaticFile("/file", ".")) assert.Equal(t, r, r.StaticFileFS("/static2", ".", Dir(".", false))) assert.Equal(t, r, r.Static("/static", ".")) assert.Equal(t, r, r.StaticFS("/static2", Dir(".", false))) } func TestRouterGroupCombineHandlersTooManyHandlers(t *testing.T) { group := &RouterGroup{ Handlers: make(HandlersChain, MaxHandlers), // Assume group already has MaxHandlers middleware } tooManyHandlers := make(HandlersChain, MaxHandlers) // Add MaxHandlers more, total 2 * MaxHandlers // This should trigger panic assert.Panics(t, func() { group.combineHandlers(tooManyHandlers) }, "should panic due to too many handlers") } func TestRouterGroupCombineHandlersEmptySliceNotNil(t *testing.T) { group := &RouterGroup{ Handlers: HandlersChain{}, } result := group.combineHandlers(HandlersChain{}) assert.NotNil(t, result, "result should not be nil even with empty handlers") assert.Empty(t, result, "empty handlers should return empty chain") }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/errors_test.go
errors_test.go
// 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 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: baseError, Type: ErrorTypePrivate, } assert.Equal(t, err.Error(), baseError.Error()) assert.Equal(t, H{"error": baseError.Error()}, err.JSON()) assert.Equal(t, err.SetType(ErrorTypePublic), 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", }, 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": baseError.Error(), "status": "200", "data": "some data", }, err.JSON()) err.SetMeta(H{ //nolint: errcheck "error": "custom error", "status": "200", "data": "some data", }) assert.Equal(t, H{ "error": "custom error", "status": "200", "data": "some data", }, err.JSON()) type customError struct { status string data string } err.SetMeta(customError{status: "200", data: "other data"}) //nolint: errcheck assert.Equal(t, customError{status: "200", data: "other data"}, err.JSON()) } func TestErrorSlice(t *testing.T) { errs := errorMsgs{ {Err: errors.New("first"), Type: ErrorTypePrivate}, {Err: errors.New("second"), Type: ErrorTypePrivate, Meta: "some data"}, {Err: errors.New("third"), Type: ErrorTypePublic, Meta: H{"status": "400"}}, } assert.Equal(t, errs, errs.ByType(ErrorTypeAny)) assert.Equal(t, "third", errs.Last().Error()) assert.Equal(t, []string{"first", "second", "third"}, errs.Errors()) assert.Equal(t, []string{"third"}, errs.ByType(ErrorTypePublic).Errors()) assert.Equal(t, []string{"first", "second"}, errs.ByType(ErrorTypePrivate).Errors()) assert.Equal(t, []string{"first", "second", "third"}, errs.ByType(ErrorTypePublic|ErrorTypePrivate).Errors()) assert.Empty(t, errs.ByType(ErrorTypeBind)) assert.Empty(t, errs.ByType(ErrorTypeBind).String()) assert.Equal(t, `Error #01: first Error #02: second Meta: some data Error #03: third Meta: map[status:400] `, errs.String()) assert.Equal(t, []any{ H{"error": "first"}, H{"error": "second", "meta": "some data"}, H{"error": "third", "status": "400"}, }, errs.JSON()) jsonBytes, _ := json.API.Marshal(errs) assert.JSONEq(t, "[{\"error\":\"first\"},{\"error\":\"second\",\"meta\":\"some data\"},{\"error\":\"third\",\"status\":\"400\"}]", string(jsonBytes)) errs = errorMsgs{ {Err: errors.New("first"), Type: ErrorTypePrivate}, } assert.Equal(t, H{"error": "first"}, errs.JSON()) jsonBytes, _ = json.API.Marshal(errs) assert.JSONEq(t, "{\"error\":\"first\"}", string(jsonBytes)) errs = errorMsgs{} assert.Nil(t, errs.Last()) assert.Nil(t, errs.JSON()) assert.Empty(t, errs.String()) } type TestErr string func (e TestErr) Error() string { return string(e) } // TestErrorUnwrap tests the behavior of gin.Error with "errors.Is()" and "errors.As()". // "errors.Is()" and "errors.As()" have been added to the standard library in go 1.13. func TestErrorUnwrap(t *testing.T) { innerErr := TestErr("some error") // 2 layers of wrapping : use 'fmt.Errorf("%w")' to wrap a gin.Error{}, which itself wraps innerErr err := fmt.Errorf("wrapped: %w", &Error{ Err: innerErr, Type: ErrorTypeAny, }) // check that 'errors.Is()' and 'errors.As()' behave as expected : require.ErrorIs(t, err, innerErr) var testErr TestErr require.ErrorAs(t, err, &testErr) // Test non-pointer usage of gin.Error errNonPointer := Error{ Err: innerErr, Type: ErrorTypeAny, } wrappedErr := fmt.Errorf("wrapped: %w", errNonPointer) // Check that 'errors.Is()' and 'errors.As()' behave as expected for non-pointer usage require.ErrorIs(t, wrappedErr, innerErr) var testErrNonPointer TestErr require.ErrorAs(t, wrappedErr, &testErrNonPointer) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/middleware_test.go
middleware_test.go
// 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 gin import ( "errors" "net/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" }) router.GET("/", func(c *Context) { signature += "D" }) router.NoRoute(func(c *Context) { signature += " X " }) router.NoMethod(func(c *Context) { signature += " XX " }) // RUN w := 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(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() signature += "F" }, func(c *Context) { signature += "G" c.Next() signature += "H" }) router.NoMethod(func(c *Context) { signature += " X " }) // RUN w := PerformRequest(router, http.MethodGet, "/") // TEST assert.Equal(t, http.StatusNotFound, w.Code) assert.Equal(t, "ACEGHFDB", signature) } func TestMiddlewareNoMethodEnabled(t *testing.T) { signature := "" router := New() router.HandleMethodNotAllowed = true router.Use(func(c *Context) { signature += "A" c.Next() signature += "B" }) router.Use(func(c *Context) { signature += "C" c.Next() signature += "D" }) router.NoMethod(func(c *Context) { signature += "E" c.Next() signature += "F" }, func(c *Context) { signature += "G" c.Next() signature += "H" }) router.NoRoute(func(c *Context) { signature += " X " }) router.POST("/", func(c *Context) { signature += " XX " }) // RUN w := PerformRequest(router, http.MethodGet, "/") // TEST assert.Equal(t, http.StatusMethodNotAllowed, w.Code) assert.Equal(t, "ACEGHFDB", signature) } func TestMiddlewareNoMethodDisabled(t *testing.T) { signature := "" router := New() // NoMethod disabled router.HandleMethodNotAllowed = false router.Use(func(c *Context) { signature += "A" c.Next() signature += "B" }) router.Use(func(c *Context) { signature += "C" c.Next() signature += "D" }) router.NoMethod(func(c *Context) { signature += "E" c.Next() signature += "F" }, func(c *Context) { signature += "G" c.Next() signature += "H" }) router.NoRoute(func(c *Context) { signature += " X " }) router.POST("/", func(c *Context) { signature += " XX " }) // RUN w := PerformRequest(router, http.MethodGet, "/") // TEST assert.Equal(t, http.StatusNotFound, w.Code) assert.Equal(t, "AC X DB", signature) } func TestMiddlewareAbort(t *testing.T) { signature := "" router := New() router.Use(func(c *Context) { signature += "A" }) router.Use(func(c *Context) { signature += "C" c.AbortWithStatus(http.StatusUnauthorized) c.Next() signature += "D" }) router.GET("/", func(c *Context) { signature += " X " c.Next() signature += " XX " }) // RUN w := PerformRequest(router, http.MethodGet, "/") // TEST assert.Equal(t, http.StatusUnauthorized, w.Code) assert.Equal(t, "ACD", signature) } func TestMiddlewareAbortHandlersChainAndNext(t *testing.T) { signature := "" router := New() router.Use(func(c *Context) { signature += "A" c.Next() c.AbortWithStatus(http.StatusGone) signature += "B" }) router.GET("/", func(c *Context) { signature += "C" c.Next() }) // RUN w := PerformRequest(router, http.MethodGet, "/") // TEST assert.Equal(t, http.StatusGone, w.Code) assert.Equal(t, "ACB", signature) } // TestMiddlewareFailHandlersChain - ensure that Fail interrupt used middleware in fifo order as // as well as Abort func TestMiddlewareFailHandlersChain(t *testing.T) { // SETUP signature := "" router := New() router.Use(func(context *Context) { signature += "A" context.AbortWithError(http.StatusInternalServerError, errors.New("foo")) //nolint: errcheck }) router.Use(func(context *Context) { signature += "B" context.Next() signature += "C" }) // RUN w := PerformRequest(router, http.MethodGet, "/") // TEST assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Equal(t, "A", signature) } func TestMiddlewareWrite(t *testing.T) { router := New() router.Use(func(c *Context) { c.String(http.StatusBadRequest, "hola\n") }) router.Use(func(c *Context) { c.XML(http.StatusBadRequest, H{"foo": "bar"}) }) router.Use(func(c *Context) { c.JSON(http.StatusBadRequest, H{"foo": "bar"}) }) router.GET("/", func(c *Context) { c.JSON(http.StatusBadRequest, H{"foo": "bar"}) }, func(c *Context) { c.Render(http.StatusBadRequest, sse.Event{ Event: "test", Data: "message", }) }) w := PerformRequest(router, http.MethodGet, "/") assert.Equal(t, http.StatusBadRequest, w.Code) assert.Equal(t, strings.ReplaceAll("hola\n<map><foo>bar</foo></map>{\"foo\":\"bar\"}{\"foo\":\"bar\"}event:test\ndata:message\n\n", " ", ""), strings.ReplaceAll(w.Body.String(), " ", "")) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/test_helpers.go
test_helpers.go
// Copyright 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 ( "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 a new Gin engine instance // along with a context, for example, to test middleware that doesn't depend on // specific routes. The ResponseWriter `w` is used to initialize the context's writer. 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 provided 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 the `maxParams` setting from the provided engine. func CreateTestContextOnly(w http.ResponseWriter, r *Engine) (c *Context) { c = r.allocateContext(r.maxParams) c.reset() c.writermem.reset(w) return } // waitForServerReady waits for a server to be ready by making HTTP requests // with exponential backoff. This is more reliable than time.Sleep() for testing. func waitForServerReady(url string, maxAttempts int) error { client := &http.Client{ Timeout: 100 * time.Millisecond, } for i := 0; i < maxAttempts; i++ { resp, err := client.Get(url) if err == nil { resp.Body.Close() return nil } // Exponential backoff: 10ms, 20ms, 40ms, 80ms, 160ms... backoff := time.Duration(10*(1<<uint(i))) * time.Millisecond if backoff > 500*time.Millisecond { backoff = 500 * time.Millisecond } time.Sleep(backoff) } return fmt.Errorf("server at %s did not become ready after %d attempts", url, maxAttempts) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/path.go
path.go
// Copyright 2013 Julien Schmidt. All rights reserved. // Based on the path package, Copyright 2009 The 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 .. elements. // // The following rules are applied iteratively until no further processing can // be done: // 1. Replace multiple slashes with a single slash. // 2. Eliminate each . path name element (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, replace "/.." 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 avoid allocations in the common case. // If a larger buffer is required, it gets allocated dynamically. buf := make([]byte, 0, stackBufSize) n := len(p) // Invariants: // reading from path; r is index of next byte to process. // writing to buf; w is index of next byte to write. // path must start with '/' r := 1 w := 1 if p[0] != '/' { r = 0 if n+1 > stackBufSize { buf = make([]byte, n+1) } else { buf = buf[:n+1] } buf[0] = '/' } trailing := n > 1 && p[n-1] == '/' // A bit more clunky without a 'lazybuf' like the path package, but the loop // gets completely inlined (bufApp calls). // loop has no expensive function calls (except 1x make) // So in contrast to the path package this loop has no expensive function // calls (except make, if needed). for r < n { switch { case p[r] == '/': // empty path element, trailing slash is added after the end r++ case p[r] == '.' && r+1 == n: trailing = true r++ case p[r] == '.' && p[r+1] == '/': // . element r += 2 case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'): // .. element: remove to last / r += 3 if w > 1 { // can backtrack w-- if len(buf) == 0 { for w > 1 && p[w] != '/' { w-- } } else { for w > 1 && buf[w] != '/' { w-- } } } default: // Real path element. // Add slash if needed if w > 1 { bufApp(&buf, p, w, '/') w++ } // Copy element for r < n && p[r] != '/' { bufApp(&buf, p, w, p[r]) w++ r++ } } } // Re-append trailing slash if trailing && w > 1 { bufApp(&buf, p, w, '/') w++ } // If the original string was not modified (or only shortened at the end), // return the respective substring of the original string. // Otherwise return a new string from the buffer. if len(buf) == 0 { return p[:w] } return string(buf[:w]) } // Internal helper to lazily create a buffer if necessary. // Calls to this function get inlined. func bufApp(buf *[]byte, s string, w int, c byte) { b := *buf if len(b) == 0 { // No modification of the original string so far. // If the next character is the same as in the original string, we do // not yet have to allocate a buffer. if s[w] == c { return } // Otherwise use either the stack buffer, if it is large enough, or // allocate a new buffer on the heap, and copy all previous characters. length := len(s) if length > cap(b) { *buf = make([]byte, length) } else { *buf = (*buf)[:length] } b = *buf copy(b, s[:w]) } b[w] = c } // removeRepeatedChar removes multiple consecutive 'char's from a string. // if s == "/a//b///c////" && char == '/', it returns "/a/b/c/" func removeRepeatedChar(s string, char byte) string { // Check if there are any consecutive chars hasRepeatedChar := false for i := 1; i < len(s); i++ { if s[i] == char && s[i-1] == char { hasRepeatedChar = true break } } if !hasRepeatedChar { return s } // Reasonably sized buffer on stack to avoid allocations in the common case. buf := make([]byte, 0, stackBufSize) // Invariants: // reading from s; r is index of next byte to process. // writing to buf; w is index of next byte to write. r := 0 w := 0 for n := len(s); r < n; { if s[r] == char { // Write the first char bufApp(&buf, s, w, char) w++ r++ // Skip all consecutive chars for r < n && s[r] == char { r++ } } else { // Copy non-char character bufApp(&buf, s, w, s[r]) w++ r++ } } // If the original string was not modified (or only shortened at the end), // return the respective substring of the original string. // Otherwise, return a new string from the buffer. if len(buf) == 0 { return s[:w] } return string(buf[:w]) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/githubapi_test.go
githubapi_test.go
// 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 gin import ( "fmt" "math/rand" "net/http" "net/http/httptest" "os" "strconv" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) type route struct { method string path string } // http://developer.github.com/v3/ var githubAPI = []route{ // OAuth Authorizations {http.MethodGet, "/authorizations"}, {http.MethodGet, "/authorizations/:id"}, {http.MethodPost, "/authorizations"}, //{http.MethodPut, "/authorizations/clients/:client_id"}, //{http.MethodPatch, "/authorizations/:id"}, {http.MethodDelete, "/authorizations/:id"}, {http.MethodGet, "/applications/:client_id/tokens/: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/events"}, {http.MethodGet, "/users/:user/received_events"}, {http.MethodGet, "/users/:user/received_events/public"}, {http.MethodGet, "/users/:user/events"}, {http.MethodGet, "/users/:user/events/public"}, {http.MethodGet, "/users/:user/events/orgs/:org"}, {http.MethodGet, "/feeds"}, {http.MethodGet, "/notifications"}, {http.MethodGet, "/repos/:owner/:repo/notifications"}, {http.MethodPut, "/notifications"}, {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/threads/:id/subscription"}, {http.MethodDelete, "/notifications/threads/:id/subscription"}, {http.MethodGet, "/repos/:owner/:repo/stargazers"}, {http.MethodGet, "/users/:user/starred"}, {http.MethodGet, "/user/starred"}, {http.MethodGet, "/user/starred/:owner/:repo"}, {http.MethodPut, "/user/starred/:owner/:repo"}, {http.MethodDelete, "/user/starred/:owner/:repo"}, {http.MethodGet, "/repos/:owner/:repo/subscribers"}, {http.MethodGet, "/users/:user/subscriptions"}, {http.MethodGet, "/user/subscriptions"}, {http.MethodGet, "/repos/:owner/:repo/subscription"}, {http.MethodPut, "/repos/:owner/:repo/subscription"}, {http.MethodDelete, "/repos/:owner/:repo/subscription"}, {http.MethodGet, "/user/subscriptions/:owner/:repo"}, {http.MethodPut, "/user/subscriptions/:owner/:repo"}, {http.MethodDelete, "/user/subscriptions/:owner/:repo"}, // Gists {http.MethodGet, "/users/:user/gists"}, {http.MethodGet, "/gists"}, //{http.MethodGet, "/gists/public"}, //{http.MethodGet, "/gists/starred"}, {http.MethodGet, "/gists/:id"}, {http.MethodPost, "/gists"}, //{http.MethodPatch, "/gists/:id"}, {http.MethodPut, "/gists/:id/star"}, {http.MethodDelete, "/gists/:id/star"}, {http.MethodGet, "/gists/:id/star"}, {http.MethodPost, "/gists/:id/forks"}, {http.MethodDelete, "/gists/:id"}, // Git Data {http.MethodGet, "/repos/:owner/:repo/git/blobs/:sha"}, {http.MethodPost, "/repos/:owner/:repo/git/blobs"}, {http.MethodGet, "/repos/:owner/:repo/git/commits/:sha"}, {http.MethodPost, "/repos/:owner/:repo/git/commits"}, //{http.MethodGet, "/repos/:owner/:repo/git/refs/*ref"}, {http.MethodGet, "/repos/:owner/:repo/git/refs"}, {http.MethodPost, "/repos/:owner/:repo/git/refs"}, //{http.MethodPatch, "/repos/:owner/:repo/git/refs/*ref"}, //{http.MethodDelete, "/repos/:owner/:repo/git/refs/*ref"}, {http.MethodGet, "/repos/:owner/:repo/git/tags/:sha"}, {http.MethodPost, "/repos/:owner/:repo/git/tags"}, {http.MethodGet, "/repos/:owner/:repo/git/trees/:sha"}, {http.MethodPost, "/repos/:owner/:repo/git/trees"}, // Issues {http.MethodGet, "/issues"}, {http.MethodGet, "/user/issues"}, {http.MethodGet, "/orgs/:org/issues"}, {http.MethodGet, "/repos/:owner/:repo/issues"}, {http.MethodGet, "/repos/:owner/:repo/issues/:number"}, {http.MethodPost, "/repos/:owner/:repo/issues"}, //{http.MethodPatch, "/repos/:owner/:repo/issues/:number"}, {http.MethodGet, "/repos/:owner/:repo/assignees"}, {http.MethodGet, "/repos/:owner/:repo/assignees/:assignee"}, {http.MethodGet, "/repos/:owner/:repo/issues/:number/comments"}, //{http.MethodGet, "/repos/:owner/:repo/issues/comments"}, //{http.MethodGet, "/repos/:owner/:repo/issues/comments/:id"}, {http.MethodPost, "/repos/:owner/:repo/issues/:number/comments"}, //{http.MethodPatch, "/repos/:owner/:repo/issues/comments/:id"}, //{http.MethodDelete, "/repos/:owner/:repo/issues/comments/:id"}, {http.MethodGet, "/repos/:owner/:repo/issues/:number/events"}, //{http.MethodGet, "/repos/:owner/:repo/issues/events"}, //{http.MethodGet, "/repos/:owner/:repo/issues/events/:id"}, {http.MethodGet, "/repos/:owner/:repo/labels"}, {http.MethodGet, "/repos/:owner/:repo/labels/:name"}, {http.MethodPost, "/repos/:owner/:repo/labels"}, //{http.MethodPatch, "/repos/:owner/:repo/labels/:name"}, {http.MethodDelete, "/repos/:owner/:repo/labels/:name"}, {http.MethodGet, "/repos/:owner/:repo/issues/:number/labels"}, {http.MethodPost, "/repos/:owner/:repo/issues/:number/labels"}, {http.MethodDelete, "/repos/:owner/:repo/issues/:number/labels/:name"}, {http.MethodPut, "/repos/:owner/:repo/issues/:number/labels"}, {http.MethodDelete, "/repos/:owner/:repo/issues/:number/labels"}, {http.MethodGet, "/repos/:owner/:repo/milestones/:number/labels"}, {http.MethodGet, "/repos/:owner/:repo/milestones"}, {http.MethodGet, "/repos/:owner/:repo/milestones/:number"}, {http.MethodPost, "/repos/:owner/:repo/milestones"}, //{http.MethodPatch, "/repos/:owner/:repo/milestones/:number"}, {http.MethodDelete, "/repos/:owner/:repo/milestones/:number"}, // Miscellaneous {http.MethodGet, "/emojis"}, {http.MethodGet, "/gitignore/templates"}, {http.MethodGet, "/gitignore/templates/:name"}, {http.MethodPost, "/markdown"}, {http.MethodPost, "/markdown/raw"}, {http.MethodGet, "/meta"}, {http.MethodGet, "/rate_limit"}, // Organizations {http.MethodGet, "/users/:user/orgs"}, {http.MethodGet, "/user/orgs"}, {http.MethodGet, "/orgs/:org"}, //{http.MethodPatch, "/orgs/:org"}, {http.MethodGet, "/orgs/:org/members"}, {http.MethodGet, "/orgs/:org/members/:user"}, {http.MethodDelete, "/orgs/:org/members/:user"}, {http.MethodGet, "/orgs/:org/public_members"}, {http.MethodGet, "/orgs/:org/public_members/:user"}, {http.MethodPut, "/orgs/:org/public_members/:user"}, {http.MethodDelete, "/orgs/:org/public_members/:user"}, {http.MethodGet, "/orgs/:org/teams"}, {http.MethodGet, "/teams/:id"}, {http.MethodPost, "/orgs/:org/teams"}, //{http.MethodPatch, "/teams/:id"}, {http.MethodDelete, "/teams/:id"}, {http.MethodGet, "/teams/:id/members"}, {http.MethodGet, "/teams/:id/members/:user"}, {http.MethodPut, "/teams/:id/members/:user"}, {http.MethodDelete, "/teams/:id/members/:user"}, {http.MethodGet, "/teams/:id/repos"}, {http.MethodGet, "/teams/:id/repos/:owner/:repo"}, {http.MethodPut, "/teams/:id/repos/:owner/:repo"}, {http.MethodDelete, "/teams/:id/repos/:owner/:repo"}, {http.MethodGet, "/user/teams"}, // Pull Requests {http.MethodGet, "/repos/:owner/:repo/pulls"}, {http.MethodGet, "/repos/:owner/:repo/pulls/:number"}, {http.MethodPost, "/repos/:owner/:repo/pulls"}, //{http.MethodPatch, "/repos/:owner/:repo/pulls/:number"}, {http.MethodGet, "/repos/:owner/:repo/pulls/:number/commits"}, {http.MethodGet, "/repos/:owner/:repo/pulls/:number/files"}, {http.MethodGet, "/repos/:owner/:repo/pulls/:number/merge"}, {http.MethodPut, "/repos/:owner/:repo/pulls/:number/merge"}, {http.MethodGet, "/repos/:owner/:repo/pulls/:number/comments"}, //{http.MethodGet, "/repos/:owner/:repo/pulls/comments"}, //{http.MethodGet, "/repos/:owner/:repo/pulls/comments/:number"}, {http.MethodPut, "/repos/:owner/:repo/pulls/:number/comments"}, //{http.MethodPatch, "/repos/:owner/:repo/pulls/comments/:number"}, //{http.MethodDelete, "/repos/:owner/:repo/pulls/comments/:number"}, // Repositories {http.MethodGet, "/user/repos"}, {http.MethodGet, "/users/:user/repos"}, {http.MethodGet, "/orgs/:org/repos"}, {http.MethodGet, "/repositories"}, {http.MethodPost, "/user/repos"}, {http.MethodPost, "/orgs/:org/repos"}, {http.MethodGet, "/repos/:owner/:repo"}, //{http.MethodPatch, "/repos/:owner/:repo"}, {http.MethodGet, "/repos/:owner/:repo/contributors"}, {http.MethodGet, "/repos/:owner/:repo/languages"}, {http.MethodGet, "/repos/:owner/:repo/teams"}, {http.MethodGet, "/repos/:owner/:repo/tags"}, {http.MethodGet, "/repos/:owner/:repo/branches"}, {http.MethodGet, "/repos/:owner/:repo/branches/:branch"}, {http.MethodDelete, "/repos/:owner/:repo"}, {http.MethodGet, "/repos/:owner/:repo/collaborators"}, {http.MethodGet, "/repos/:owner/:repo/collaborators/:user"}, {http.MethodPut, "/repos/:owner/:repo/collaborators/:user"}, {http.MethodDelete, "/repos/:owner/:repo/collaborators/:user"}, {http.MethodGet, "/repos/:owner/:repo/comments"}, {http.MethodGet, "/repos/:owner/:repo/commits/:sha/comments"}, {http.MethodPost, "/repos/:owner/:repo/commits/:sha/comments"}, {http.MethodGet, "/repos/:owner/:repo/comments/:id"}, //{http.MethodPatch, "/repos/:owner/:repo/comments/:id"}, {http.MethodDelete, "/repos/:owner/:repo/comments/:id"}, {http.MethodGet, "/repos/:owner/:repo/commits"}, {http.MethodGet, "/repos/:owner/:repo/commits/:sha"}, {http.MethodGet, "/repos/:owner/:repo/readme"}, //{http.MethodGet, "/repos/:owner/:repo/contents/*path"}, //{http.MethodPut, "/repos/:owner/:repo/contents/*path"}, //{http.MethodDelete, "/repos/:owner/:repo/contents/*path"}, //{http.MethodGet, "/repos/:owner/:repo/:archive_format/:ref"}, {http.MethodGet, "/repos/:owner/:repo/keys"}, {http.MethodGet, "/repos/:owner/:repo/keys/:id"}, {http.MethodPost, "/repos/:owner/:repo/keys"}, //{http.MethodPatch, "/repos/:owner/:repo/keys/:id"}, {http.MethodDelete, "/repos/:owner/:repo/keys/:id"}, {http.MethodGet, "/repos/:owner/:repo/downloads"}, {http.MethodGet, "/repos/:owner/:repo/downloads/:id"}, {http.MethodDelete, "/repos/:owner/:repo/downloads/:id"}, {http.MethodGet, "/repos/:owner/:repo/forks"}, {http.MethodPost, "/repos/:owner/:repo/forks"}, {http.MethodGet, "/repos/:owner/:repo/hooks"}, {http.MethodGet, "/repos/:owner/:repo/hooks/:id"}, {http.MethodPost, "/repos/:owner/:repo/hooks"}, //{http.MethodPatch, "/repos/:owner/:repo/hooks/:id"}, {http.MethodPost, "/repos/:owner/:repo/hooks/:id/tests"}, {http.MethodDelete, "/repos/:owner/:repo/hooks/:id"}, {http.MethodPost, "/repos/:owner/:repo/merges"}, {http.MethodGet, "/repos/:owner/:repo/releases"}, {http.MethodGet, "/repos/:owner/:repo/releases/:id"}, {http.MethodPost, "/repos/:owner/:repo/releases"}, //{http.MethodPatch, "/repos/:owner/:repo/releases/:id"}, {http.MethodDelete, "/repos/:owner/:repo/releases/:id"}, {http.MethodGet, "/repos/:owner/:repo/releases/:id/assets"}, {http.MethodGet, "/repos/:owner/:repo/stats/contributors"}, {http.MethodGet, "/repos/:owner/:repo/stats/commit_activity"}, {http.MethodGet, "/repos/:owner/:repo/stats/code_frequency"}, {http.MethodGet, "/repos/:owner/:repo/stats/participation"}, {http.MethodGet, "/repos/:owner/:repo/stats/punch_card"}, {http.MethodGet, "/repos/:owner/:repo/statuses/:ref"}, {http.MethodPost, "/repos/:owner/:repo/statuses/:ref"}, // Search {http.MethodGet, "/search/repositories"}, {http.MethodGet, "/search/code"}, {http.MethodGet, "/search/issues"}, {http.MethodGet, "/search/users"}, {http.MethodGet, "/legacy/issues/search/:owner/:repository/:state/:keyword"}, {http.MethodGet, "/legacy/repos/search/:keyword"}, {http.MethodGet, "/legacy/user/search/:keyword"}, {http.MethodGet, "/legacy/user/email/:email"}, // Users {http.MethodGet, "/users/:user"}, {http.MethodGet, "/user"}, //{http.MethodPatch, "/user"}, {http.MethodGet, "/users"}, {http.MethodGet, "/user/emails"}, {http.MethodPost, "/user/emails"}, {http.MethodDelete, "/user/emails"}, {http.MethodGet, "/users/:user/followers"}, {http.MethodGet, "/user/followers"}, {http.MethodGet, "/users/:user/following"}, {http.MethodGet, "/user/following"}, {http.MethodGet, "/user/following/:user"}, {http.MethodGet, "/users/:user/following/:target_user"}, {http.MethodPut, "/user/following/:user"}, {http.MethodDelete, "/user/following/:user"}, {http.MethodGet, "/users/:user/keys"}, {http.MethodGet, "/user/keys"}, {http.MethodGet, "/user/keys/:id"}, {http.MethodPost, "/user/keys"}, //{http.MethodPatch, "/user/keys/:id"}, {http.MethodDelete, "/user/keys/:id"}, } func TestShouldBindUri(t *testing.T) { DefaultWriter = os.Stdout router := New() type Person struct { Name string `uri:"name" binding:"required"` ID string `uri:"id" binding:"required"` } router.Handle(http.MethodGet, "/rest/:name/:id", func(c *Context) { var person Person require.NoError(t, c.ShouldBindUri(&person)) assert.NotEmpty(t, person.Name) assert.NotEmpty(t, person.ID) c.String(http.StatusOK, "ShouldBindUri test OK") }) path, _ := exampleFromPath("/rest/:name/:id") w := PerformRequest(router, http.MethodGet, path) assert.Equal(t, "ShouldBindUri test OK", w.Body.String()) assert.Equal(t, http.StatusOK, w.Code) } func TestBindUri(t *testing.T) { DefaultWriter = os.Stdout router := New() type Person struct { Name string `uri:"name" binding:"required"` ID string `uri:"id" binding:"required"` } router.Handle(http.MethodGet, "/rest/:name/:id", func(c *Context) { var person Person require.NoError(t, c.BindUri(&person)) assert.NotEmpty(t, person.Name) assert.NotEmpty(t, person.ID) c.String(http.StatusOK, "BindUri test OK") }) path, _ := exampleFromPath("/rest/:name/:id") w := PerformRequest(router, http.MethodGet, path) assert.Equal(t, "BindUri test OK", w.Body.String()) assert.Equal(t, http.StatusOK, w.Code) } func TestBindUriError(t *testing.T) { DefaultWriter = os.Stdout router := New() type Member struct { Number string `uri:"num" binding:"required,uuid"` } router.Handle(http.MethodGet, "/new/rest/:num", func(c *Context) { var m Member require.Error(t, c.BindUri(&m)) }) path1, _ := exampleFromPath("/new/rest/:num") w1 := PerformRequest(router, http.MethodGet, path1) assert.Equal(t, http.StatusBadRequest, w1.Code) } func TestRaceContextCopy(t *testing.T) { DefaultWriter = os.Stdout router := Default() router.GET("/test/copy/race", func(c *Context) { c.Set("1", 0) c.Set("2", 0) // Sending a copy of the Context to two separate routines go readWriteKeys(c.Copy()) go readWriteKeys(c.Copy()) c.String(http.StatusOK, "run OK, no panics") }) w := PerformRequest(router, http.MethodGet, "/test/copy/race") assert.Equal(t, "run OK, no panics", w.Body.String()) } func readWriteKeys(c *Context) { for { c.Set("1", rand.Int()) c.Set("2", c.Value("1")) } } func githubConfigRouter(router *Engine) { for _, route := range githubAPI { router.Handle(route.method, route.path, func(c *Context) { output := make(map[string]string, len(c.Params)+1) output["status"] = "good" for _, param := range c.Params { output[param.Key] = param.Value } c.JSON(http.StatusOK, output) }) } } func TestGithubAPI(t *testing.T) { DefaultWriter = os.Stdout router := New() githubConfigRouter(router) for _, route := range githubAPI { path, values := exampleFromPath(route.path) w := PerformRequest(router, route.method, path) // TEST assert.Contains(t, w.Body.String(), "\"status\":\"good\"") for _, value := range values { str := fmt.Sprintf("\"%s\":\"%s\"", value.Key, value.Value) assert.Contains(t, w.Body.String(), str) } } } func exampleFromPath(path string) (string, Params) { output := new(strings.Builder) params := make(Params, 0, 6) start := -1 for i, c := range path { if c == ':' { start = i + 1 } if start >= 0 { if c == '/' { value := strconv.Itoa(rand.Intn(100000)) params = append(params, Param{ Key: path[start:i], Value: value, }) output.WriteString(value) output.WriteRune(c) start = -1 } } else { output.WriteRune(c) } } if start >= 0 { value := strconv.Itoa(rand.Intn(100000)) params = append(params, Param{ Key: path[start:], Value: value, }) output.WriteString(value) } return output.String(), params } func BenchmarkGithub(b *testing.B) { router := New() githubConfigRouter(router) runRequest(b, router, http.MethodGet, "/legacy/issues/search/:owner/:repository/:state/:keyword") } func BenchmarkParallelGithub(b *testing.B) { DefaultWriter = os.Stdout router := New() githubConfigRouter(router) req, _ := http.NewRequest(http.MethodPost, "/repos/manucorporat/sse/git/blobs", nil) b.RunParallel(func(pb *testing.PB) { // Each goroutine has its own bytes.Buffer. for pb.Next() { w := httptest.NewRecorder() router.ServeHTTP(w, req) } }) } func BenchmarkParallelGithubDefault(b *testing.B) { DefaultWriter = os.Stdout router := New() githubConfigRouter(router) req, _ := http.NewRequest(http.MethodPost, "/repos/manucorporat/sse/git/blobs", nil) b.RunParallel(func(pb *testing.PB) { // Each goroutine has its own bytes.Buffer. for pb.Next() { w := httptest.NewRecorder() router.ServeHTTP(w, req) } }) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/recovery.go
recovery.go
// 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 gin import ( "bufio" "bytes" "cmp" "errors" "fmt" "io" "log" "net" "net/http" "net/http/httputil" "os" "runtime" "strings" "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 any) // Recovery returns a middleware that recovers from any panics and writes a 500 if there was one. func Recovery() HandlerFunc { return RecoveryWithWriter(DefaultErrorWriter) } // CustomRecovery 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) } // RecoveryWithWriter 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 CustomRecoveryWithWriter(out, recovery[0]) } return CustomRecoveryWithWriter(out, defaultHandleRecovery) } // CustomRecoveryWithWriter returns a middleware for a given writer that recovers from any panics and calls the provided handle func to handle it. func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc { var logger *log.Logger if out != nil { logger = log.New(out, "\n\n\x1b[31m", log.LstdFlags) } return func(c *Context) { defer func() { if err := recover(); err != nil { // Check for a broken connection, as it is not really a // condition that warrants a panic stack trace. var brokenPipe bool if ne, ok := err.(*net.OpError); ok { var se *os.SyscallError if errors.As(ne, &se) { seStr := strings.ToLower(se.Error()) if strings.Contains(seStr, "broken pipe") || strings.Contains(seStr, "connection reset by peer") { brokenPipe = true } } } if e, ok := err.(error); ok && errors.Is(e, http.ErrAbortHandler) { brokenPipe = true } if logger != nil { if brokenPipe { logger.Printf("%s\n%s%s", err, secureRequestDump(c.Request), reset) } else if IsDebugging() { logger.Printf("[Recovery] %s panic recovered:\n%s\n%s\n%s%s", timeFormat(time.Now()), secureRequestDump(c.Request), err, stack(stackSkip), reset) } else { logger.Printf("[Recovery] %s panic recovered:\n%s\n%s%s", timeFormat(time.Now()), err, stack(stackSkip), reset) } } if brokenPipe { // If the connection is dead, we can't write a status to it. c.Error(err.(error)) //nolint: errcheck c.Abort() } else { handle(c, err) } } }() c.Next() } } // secureRequestDump returns a sanitized HTTP request dump where the Authorization header, // if present, is replaced with a masked value ("Authorization: *") to avoid leaking sensitive credentials. // // Currently, only the Authorization header is sanitized. All other headers and request data remain unchanged. func secureRequestDump(r *http.Request) string { httpRequest, _ := httputil.DumpRequest(r, false) lines := strings.Split(bytesconv.BytesToString(httpRequest), "\r\n") for i, line := range lines { if strings.HasPrefix(line, "Authorization:") { lines[i] = "Authorization: *" } } return strings.Join(lines, "\r\n") } func defaultHandleRecovery(c *Context, _ any) { c.AbortWithStatus(http.StatusInternalServerError) } // stack returns a nicely formatted stack frame, skipping skip frames. func stack(skip int) []byte { buf := new(bytes.Buffer) // the returned data // As we loop, we open files and read them. These variables record the currently // loaded file. var ( nLine string lastFile string err error ) for i := skip; ; i++ { // Skip the expected number of frames pc, file, line, ok := runtime.Caller(i) if !ok { break } // Print this much at least. If we can't find the source, it won't show. fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc) if file != lastFile { nLine, err = readNthLine(file, line-1) if err != nil { continue } lastFile = file } fmt.Fprintf(buf, "\t%s: %s\n", function(pc), cmp.Or(nLine, dunno)) } return buf.Bytes() } // readNthLine reads the nth line from the file. // It returns the trimmed content of the line if found, // or an empty string if the line doesn't exist. // If there's an error opening the file, it returns the error. func readNthLine(file string, n int) (string, error) { if n < 0 { return "", nil } f, err := os.Open(file) if err != nil { return "", err } defer f.Close() scanner := bufio.NewScanner(f) for i := 0; i < n; i++ { if !scanner.Scan() { return "", nil } } if scanner.Scan() { return strings.TrimSpace(scanner.Text()), nil } return "", nil } // function returns, if possible, the name of the function containing the PC. func function(pc uintptr) string { fn := runtime.FuncForPC(pc) if fn == nil { return dunno } name := fn.Name() // The name includes the path name to the package, which is unnecessary // since the file name is already included. Plus, it has center dots. // That is, we see // runtime/debug.*TΒ·ptrmethod // and want // *T.ptrmethod // Also the package path might contain dot (e.g. code.google.com/...), // so first eliminate the path prefix if lastSlash := strings.LastIndexByte(name, '/'); lastSlash >= 0 { name = name[lastSlash+1:] } if period := strings.IndexByte(name, '.'); period >= 0 { name = name[period+1:] } name = strings.ReplaceAll(name, "Β·", ".") return name } // timeFormat returns a customized time string for logger. func timeFormat(t time.Time) string { return t.Format("2006/01/02 - 15:04:05") }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/errors.go
errors.go
// 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 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. ErrorTypeBind ErrorType = 1 << 63 // ErrorTypeRender is used when Context.Render() fails. ErrorTypeRender ErrorType = 1 << 62 // ErrorTypePrivate indicates a private error. ErrorTypePrivate ErrorType = 1 << 0 // ErrorTypePublic indicates a public error. ErrorTypePublic ErrorType = 1 << 1 // ErrorTypeAny indicates any other error. ErrorTypeAny ErrorType = 1<<64 - 1 // ErrorTypeNu indicates any other error. ErrorTypeNu = 2 ) // Error represents a error's specification. 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 error's meta data. func (msg *Error) SetMeta(data any) *Error { msg.Meta = data return msg } // JSON creates a properly formatted JSON func (msg *Error) JSON() any { jsonData := H{} if msg.Meta != nil { value := reflect.ValueOf(msg.Meta) switch value.Kind() { case reflect.Struct: return msg.Meta case reflect.Map: for _, key := range value.MapKeys() { jsonData[key.String()] = value.MapIndex(key).Interface() } default: jsonData["meta"] = msg.Meta } } if _, ok := jsonData["error"]; !ok { jsonData["error"] = msg.Error() } return jsonData } // MarshalJSON implements the json.Marshaller interface. func (msg *Error) MarshalJSON() ([]byte, error) { return json.API.Marshal(msg.JSON()) } // Error implements the error interface. func (msg Error) Error() string { return msg.Err.Error() } // IsType judges one error. func (msg *Error) IsType(flags ErrorType) bool { return (msg.Type & flags) > 0 } // Unwrap returns the wrapped error, to allow interoperability with errors.Is(), errors.As() and errors.Unwrap() func (msg Error) Unwrap() error { return msg.Err } // ByType returns a readonly copy filtered the byte. // ie ByType(gin.ErrorTypePublic) returns a slice of errors with type=ErrorTypePublic. func (a errorMsgs) ByType(typ ErrorType) errorMsgs { if len(a) == 0 { return nil } if typ == ErrorTypeAny { return a } var result errorMsgs for _, msg := range a { if msg.IsType(typ) { result = append(result, msg) } } return result } // Last returns the last error in the slice. It returns nil if the array is empty. // Shortcut for errors[len(errors)-1]. func (a errorMsgs) Last() *Error { if length := len(a); length > 0 { return a[length-1] } return nil } // Errors returns an array with all the error messages. // Example: // // c.Error(errors.New("first")) // c.Error(errors.New("second")) // c.Error(errors.New("third")) // c.Errors.Errors() // == []string{"first", "second", "third"} func (a errorMsgs) Errors() []string { if len(a) == 0 { return nil } errorStrings := make([]string, len(a)) for i, err := range a { errorStrings[i] = err.Error() } return errorStrings } func (a errorMsgs) JSON() any { switch length := len(a); length { case 0: return nil case 1: return a.Last().JSON() default: jsonData := make([]any, length) for i, err := range a { jsonData[i] = err.JSON() } return jsonData } } // MarshalJSON implements the json.Marshaller interface. func (a errorMsgs) MarshalJSON() ([]byte, error) { return json.API.Marshal(a.JSON()) } func (a errorMsgs) String() string { if len(a) == 0 { return "" } var buffer strings.Builder for i, msg := range a { fmt.Fprintf(&buffer, "Error #%02d: %s\n", i+1, msg.Err) if msg.Meta != nil { fmt.Fprintf(&buffer, " Meta: %v\n", msg.Meta) } } return buffer.String() }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/context_test.go
context_test.go
// 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 gin import ( "bytes" "context" "errors" "fmt" "html/template" "io" "io/fs" "mime/multipart" "net" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "reflect" "strconv" "strings" "sync" "testing" "time" "github.com/gin-contrib/sse" "github.com/gin-gonic/gin/binding" "github.com/gin-gonic/gin/codec/json" testdata "github.com/gin-gonic/gin/testdata/protoexample" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" ) var _ context.Context = (*Context)(nil) var errTestRender = errors.New("TestRender") // Unit tests TODO // func (c *Context) File(filepath string) { // func (c *Context) Negotiate(code int, config Negotiate) { // BAD case: func (c *Context) Render(code int, render render.Render, obj ...any) { // test that information is not leaked when reusing Contexts (using the Pool) func createMultipartRequest() *http.Request { boundary := "--testboundary" body := new(bytes.Buffer) mw := multipart.NewWriter(body) defer mw.Close() must(mw.SetBoundary(boundary)) must(mw.WriteField("foo", "bar")) must(mw.WriteField("bar", "10")) must(mw.WriteField("bar", "foo2")) must(mw.WriteField("array", "first")) must(mw.WriteField("array", "second")) must(mw.WriteField("id", "")) must(mw.WriteField("time_local", "31/12/2016 14:55")) must(mw.WriteField("time_utc", "31/12/2016 14:55")) must(mw.WriteField("time_location", "31/12/2016 14:55")) must(mw.WriteField("names[a]", "thinkerou")) must(mw.WriteField("names[b]", "tianou")) req, err := http.NewRequest(http.MethodPost, "/", body) must(err) req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary) return req } func must(err error) { if err != nil { panic(err.Error()) } } // TestContextFile tests the Context.File() method func TestContextFile(t *testing.T) { // Test serving an existing file t.Run("serve existing file", func(t *testing.T) { // Create a temporary test file testFile := "testdata/test_file.txt" w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Request = httptest.NewRequest(http.MethodGet, "/test", nil) c.File(testFile) assert.Equal(t, http.StatusOK, w.Code) assert.Contains(t, w.Body.String(), "This is a test file") assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) }) // Test serving a non-existent file t.Run("serve non-existent file", func(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.StatusNotFound, w.Code) }) // Test serving a directory (should return 200 with directory listing or 403 Forbidden) t.Run("serve directory", func(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Request = httptest.NewRequest(http.MethodGet, "/test", nil) c.File(".") // Directory serving can return either 200 (with listing) or 403 (forbidden) assert.True(t, w.Code == http.StatusOK || w.Code == 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.StatusOK, w.Code) assert.Empty(t, w.Body.String()) // HEAD request should not return body assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) }) // Test with Range request 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.Header.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 TestContextFormFile(t *testing.T) { buf := new(bytes.Buffer) mw := multipart.NewWriter(buf) w, err := mw.CreateFormFile("file", "test") require.NoError(t, err) _, err = w.Write([]byte("test")) require.NoError(t, err) mw.Close() c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest(http.MethodPost, "/", buf) c.Request.Header.Set("Content-Type", mw.FormDataContentType()) f, err := c.FormFile("file") require.NoError(t, err) assert.Equal(t, "test", f.Filename) require.NoError(t, c.SaveUploadedFile(f, "test")) } func TestContextFormFileFailed(t *testing.T) { buf := new(bytes.Buffer) mw := multipart.NewWriter(buf) mw.Close() c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest(http.MethodPost, "/", nil) c.Request.Header.Set("Content-Type", mw.FormDataContentType()) c.engine.MaxMultipartMemory = 8 << 20 f, err := c.FormFile("file") require.Error(t, err) assert.Nil(t, f) } func TestContextMultipartForm(t *testing.T) { buf := new(bytes.Buffer) mw := multipart.NewWriter(buf) require.NoError(t, mw.WriteField("foo", "bar")) w, err := mw.CreateFormFile("file", "test") require.NoError(t, err) _, err = w.Write([]byte("test")) require.NoError(t, err) mw.Close() c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest(http.MethodPost, "/", buf) c.Request.Header.Set("Content-Type", mw.FormDataContentType()) f, err := c.MultipartForm() require.NoError(t, err) assert.NotNil(t, f) require.NoError(t, c.SaveUploadedFile(f.File["file"][0], "test")) } func TestSaveUploadedOpenFailed(t *testing.T) { buf := new(bytes.Buffer) mw := multipart.NewWriter(buf) mw.Close() c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest(http.MethodPost, "/", buf) c.Request.Header.Set("Content-Type", mw.FormDataContentType()) f := &multipart.FileHeader{ Filename: "file", } require.Error(t, c.SaveUploadedFile(f, "test")) } func TestSaveUploadedCreateFailed(t *testing.T) { buf := new(bytes.Buffer) mw := multipart.NewWriter(buf) w, err := mw.CreateFormFile("file", "test") require.NoError(t, err) _, err = w.Write([]byte("test")) require.NoError(t, err) mw.Close() c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest(http.MethodPost, "/", buf) c.Request.Header.Set("Content-Type", mw.FormDataContentType()) f, err := c.FormFile("file") require.NoError(t, err) assert.Equal(t, "test", f.Filename) require.Error(t, c.SaveUploadedFile(f, "/")) } func TestSaveUploadedFileWithPermission(t *testing.T) { buf := new(bytes.Buffer) mw := multipart.NewWriter(buf) w, err := mw.CreateFormFile("file", "permission_test") require.NoError(t, err) _, err = w.Write([]byte("permission_test")) require.NoError(t, err) mw.Close() c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest(http.MethodPost, "/", buf) c.Request.Header.Set("Content-Type", mw.FormDataContentType()) f, err := c.FormFile("file") require.NoError(t, err) assert.Equal(t, "permission_test", f.Filename) var mode fs.FileMode = 0o755 require.NoError(t, c.SaveUploadedFile(f, "permission_test", mode)) t.Cleanup(func() { assert.NoError(t, os.Remove("permission_test")) }) info, err := os.Stat(filepath.Dir("permission_test")) require.NoError(t, err) assert.Equal(t, info.Mode().Perm(), mode) } func TestSaveUploadedFileWithPermissionFailed(t *testing.T) { buf := new(bytes.Buffer) mw := multipart.NewWriter(buf) w, err := mw.CreateFormFile("file", "permission_test") require.NoError(t, err) _, err = w.Write([]byte("permission_test")) require.NoError(t, err) mw.Close() c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest(http.MethodPost, "/", buf) c.Request.Header.Set("Content-Type", mw.FormDataContentType()) f, err := c.FormFile("file") require.NoError(t, err) assert.Equal(t, "permission_test", f.Filename) var mode fs.FileMode = 0o644 require.Error(t, c.SaveUploadedFile(f, "test/permission_test", mode)) } func TestContextReset(t *testing.T) { router := New() c := router.allocateContext(0) assert.Equal(t, c.engine, router) c.index = 2 c.Writer = &responseWriter{ResponseWriter: httptest.NewRecorder()} c.Params = Params{Param{}} c.Error(errors.New("test")) //nolint: errcheck c.Set("foo", "bar") c.reset() assert.False(t, c.IsAborted()) assert.Nil(t, c.Keys) assert.Nil(t, c.Accepted) assert.Empty(t, c.Errors) assert.Empty(t, c.Errors.Errors()) assert.Empty(t, c.Errors.ByType(ErrorTypeAny)) assert.Empty(t, c.Params) assert.EqualValues(t, -1, c.index) assert.Equal(t, c.Writer.(*responseWriter), &c.writermem) } func TestContextHandlers(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) assert.Nil(t, c.handlers) assert.Nil(t, c.handlers.Last()) c.handlers = HandlersChain{} assert.NotNil(t, c.handlers) assert.Nil(t, c.handlers.Last()) f := func(c *Context) {} g := func(c *Context) {} c.handlers = HandlersChain{f} compareFunc(t, f, c.handlers.Last()) c.handlers = HandlersChain{f, g} compareFunc(t, g, c.handlers.Last()) } // TestContextSetGet tests that a parameter is set correctly on the // current context and can be retrieved using Get. func TestContextSetGet(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("foo", "bar") value, err := c.Get("foo") assert.Equal(t, "bar", value) assert.True(t, err) value, err = c.Get("foo2") assert.Nil(t, value) assert.False(t, err) assert.Equal(t, "bar", c.MustGet("foo")) assert.Panicsf(t, func() { c.MustGet("no_exist") }, "key no_exist does not exist") } func TestContextSetGetAnyKey(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) type key struct{} tests := []struct { key any }{ {1}, {int32(1)}, {int64(1)}, {uint(1)}, {float32(1)}, {key{}}, {&key{}}, } for _, tt := range tests { t.Run(reflect.TypeOf(tt.key).String(), func(t *testing.T) { c.Set(tt.key, 1) value, ok := c.Get(tt.key) assert.True(t, ok) assert.Equal(t, 1, value) }) } } func TestContextSetGetPanicsWhenKeyNotComparable(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) assert.Panics(t, func() { c.Set([]int{1}, 1) c.Set(func() {}, 1) c.Set(make(chan int), 1) }) } func TestContextSetGetValues(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("string", "this is a string") c.Set("int32", int32(-42)) c.Set("int64", int64(42424242424242)) c.Set("uint64", uint64(42)) c.Set("float32", float32(4.2)) c.Set("float64", 4.2) var a any = 1 c.Set("intInterface", a) assert.Exactly(t, "this is a string", c.MustGet("string").(string)) assert.Exactly(t, int32(-42), c.MustGet("int32").(int32)) assert.Exactly(t, int64(42424242424242), c.MustGet("int64").(int64)) assert.Exactly(t, uint64(42), c.MustGet("uint64").(uint64)) assert.InDelta(t, float32(4.2), c.MustGet("float32").(float32), 0.01) assert.InDelta(t, 4.2, c.MustGet("float64").(float64), 0.01) assert.Exactly(t, 1, c.MustGet("intInterface").(int)) } func TestContextGetString(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("string", "this is a string") assert.Equal(t, "this is a string", c.GetString("string")) } func TestContextSetGetBool(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("bool", true) assert.True(t, c.GetBool("bool")) } func TestSetGetDelete(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "example-key" value := "example-value" c.Set(key, value) val, exists := c.Get(key) assert.True(t, exists) assert.Equal(t, val, value) c.Delete(key) _, exists = c.Get(key) assert.False(t, exists) } func TestContextGetInt(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("int", 1) assert.Equal(t, 1, c.GetInt("int")) } func TestContextGetInt8(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "int8" value := int8(0x7F) c.Set(key, value) assert.Equal(t, value, c.GetInt8(key)) } func TestContextGetInt16(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "int16" value := int16(0x7FFF) c.Set(key, value) assert.Equal(t, value, c.GetInt16(key)) } func TestContextGetInt32(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "int32" value := int32(0x7FFFFFFF) c.Set(key, value) assert.Equal(t, value, c.GetInt32(key)) } func TestContextGetInt64(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("int64", int64(42424242424242)) assert.Equal(t, int64(42424242424242), c.GetInt64("int64")) } func TestContextGetUint(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("uint", uint(1)) assert.Equal(t, uint(1), c.GetUint("uint")) } func TestContextGetUint8(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "uint8" value := uint8(0xFF) c.Set(key, value) assert.Equal(t, value, c.GetUint8(key)) } func TestContextGetUint16(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "uint16" value := uint16(0xFFFF) c.Set(key, value) assert.Equal(t, value, c.GetUint16(key)) } func TestContextGetUint32(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "uint32" value := uint32(0xFFFFFFFF) c.Set(key, value) assert.Equal(t, value, c.GetUint32(key)) } func TestContextGetUint64(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("uint64", uint64(18446744073709551615)) assert.Equal(t, uint64(18446744073709551615), c.GetUint64("uint64")) } func TestContextGetFloat32(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "float32" value := float32(3.14) c.Set(key, value) assert.InDelta(t, value, c.GetFloat32(key), 0.01) } func TestContextGetFloat64(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("float64", 4.2) assert.InDelta(t, 4.2, c.GetFloat64("float64"), 0.01) } func TestContextGetTime(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) t1, _ := time.Parse("1/2/2006 15:04:05", "01/01/2017 12:00:00") c.Set("time", t1) assert.Equal(t, t1, c.GetTime("time")) } func TestContextGetDuration(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("duration", time.Second) assert.Equal(t, time.Second, c.GetDuration("duration")) } func TestContextGetIntSlice(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "int-slice" value := []int{1, 2} c.Set(key, value) assert.Equal(t, value, c.GetIntSlice(key)) } func TestContextGetInt8Slice(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "int8-slice" value := []int8{1, 2} c.Set(key, value) assert.Equal(t, value, c.GetInt8Slice(key)) } func TestContextGetInt16Slice(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "int16-slice" value := []int16{1, 2} c.Set(key, value) assert.Equal(t, value, c.GetInt16Slice(key)) } func TestContextGetInt32Slice(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "int32-slice" value := []int32{1, 2} c.Set(key, value) assert.Equal(t, value, c.GetInt32Slice(key)) } func TestContextGetInt64Slice(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "int64-slice" value := []int64{1, 2} c.Set(key, value) assert.Equal(t, value, c.GetInt64Slice(key)) } func TestContextGetUintSlice(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "uint-slice" value := []uint{1, 2} c.Set(key, value) assert.Equal(t, value, c.GetUintSlice(key)) } func TestContextGetUint8Slice(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "uint8-slice" value := []uint8{1, 2} c.Set(key, value) assert.Equal(t, value, c.GetUint8Slice(key)) } func TestContextGetUint16Slice(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "uint16-slice" value := []uint16{1, 2} c.Set(key, value) assert.Equal(t, value, c.GetUint16Slice(key)) } func TestContextGetUint32Slice(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "uint32-slice" value := []uint32{1, 2} c.Set(key, value) assert.Equal(t, value, c.GetUint32Slice(key)) } func TestContextGetUint64Slice(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "uint64-slice" value := []uint64{1, 2} c.Set(key, value) assert.Equal(t, value, c.GetUint64Slice(key)) } func TestContextGetFloat32Slice(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "float32-slice" value := []float32{1, 2} c.Set(key, value) assert.Equal(t, value, c.GetFloat32Slice(key)) } func TestContextGetFloat64Slice(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) key := "float64-slice" value := []float64{1, 2} c.Set(key, value) assert.Equal(t, value, c.GetFloat64Slice(key)) } func TestContextGetStringSlice(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Set("slice", []string{"foo"}) assert.Equal(t, []string{"foo"}, c.GetStringSlice("slice")) } func TestContextGetStringMap(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) m := make(map[string]any) m["foo"] = 1 c.Set("map", m) assert.Equal(t, m, c.GetStringMap("map")) assert.Equal(t, 1, c.GetStringMap("map")["foo"]) } func TestContextGetStringMapString(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) m := make(map[string]string) m["foo"] = "bar" c.Set("map", m) assert.Equal(t, m, c.GetStringMapString("map")) assert.Equal(t, "bar", c.GetStringMapString("map")["foo"]) } func TestContextGetStringMapStringSlice(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) m := make(map[string][]string) m["foo"] = []string{"foo"} c.Set("map", m) assert.Equal(t, m, c.GetStringMapStringSlice("map")) assert.Equal(t, []string{"foo"}, c.GetStringMapStringSlice("map")["foo"]) } func TestContextCopy(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.index = 2 c.Request, _ = http.NewRequest(http.MethodPost, "/hola", nil) c.handlers = HandlersChain{func(c *Context) {}} c.Params = Params{Param{Key: "foo", Value: "bar"}} c.Set("foo", "bar") c.fullPath = "/hola" cp := c.Copy() assert.Nil(t, cp.handlers) assert.Nil(t, cp.writermem.ResponseWriter) assert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter)) assert.Equal(t, cp.Request, c.Request) assert.Equal(t, abortIndex, cp.index) assert.Equal(t, cp.Keys, c.Keys) assert.Equal(t, cp.engine, c.engine) assert.Equal(t, cp.Params, c.Params) cp.Set("foo", "notBar") assert.NotEqual(t, cp.Keys["foo"], c.Keys["foo"]) assert.Equal(t, cp.fullPath, c.fullPath) } func TestContextHandlerName(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.handlers = HandlersChain{func(c *Context) {}, handlerNameTest} assert.Regexp(t, "^(.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest$", c.HandlerName()) } func TestContextHandlerNames(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.handlers = HandlersChain{func(c *Context) {}, nil, handlerNameTest, func(c *Context) {}, handlerNameTest2} names := c.HandlerNames() assert.Len(t, names, 4) for _, name := range names { assert.Regexp(t, `^(.*/vendor/)?(github\.com/gin-gonic/gin\.){1}(TestContextHandlerNames\.func.*){0,1}(handlerNameTest.*){0,1}`, name) } } func handlerNameTest(c *Context) { } func handlerNameTest2(c *Context) { } var handlerTest HandlerFunc = func(c *Context) { } func TestContextHandler(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.handlers = HandlersChain{func(c *Context) {}, handlerTest} assert.Equal(t, reflect.ValueOf(handlerTest).Pointer(), reflect.ValueOf(c.Handler()).Pointer()) } func TestContextQuery(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest(http.MethodGet, "http://example.com/?foo=bar&page=10&id=", nil) value, ok := c.GetQuery("foo") assert.True(t, ok) assert.Equal(t, "bar", value) assert.Equal(t, "bar", c.DefaultQuery("foo", "none")) assert.Equal(t, "bar", c.Query("foo")) value, ok = c.GetQuery("page") assert.True(t, ok) assert.Equal(t, "10", value) assert.Equal(t, "10", c.DefaultQuery("page", "0")) assert.Equal(t, "10", c.Query("page")) value, ok = c.GetQuery("id") assert.True(t, ok) assert.Empty(t, value) assert.Empty(t, c.DefaultQuery("id", "nada")) assert.Empty(t, c.Query("id")) value, ok = c.GetQuery("NoKey") assert.False(t, ok) assert.Empty(t, value) assert.Equal(t, "nada", c.DefaultQuery("NoKey", "nada")) assert.Empty(t, c.Query("NoKey")) // postform should not mess value, ok = c.GetPostForm("page") assert.False(t, ok) assert.Empty(t, value) assert.Empty(t, c.PostForm("foo")) } func TestContextInitQueryCache(t *testing.T) { validURL, err := url.Parse("https://github.com/gin-gonic/gin/pull/3969?key=value&otherkey=othervalue") require.NoError(t, err) tests := []struct { testName string testContext *Context expectedQueryCache url.Values }{ { testName: "queryCache should remain unchanged if already not nil", testContext: &Context{ queryCache: url.Values{"a": []string{"b"}}, Request: &http.Request{URL: validURL}, // valid request for evidence that values weren't extracted }, expectedQueryCache: url.Values{"a": []string{"b"}}, }, { testName: "queryCache should be empty when Request is nil", testContext: &Context{Request: nil}, // explicit nil for readability expectedQueryCache: url.Values{}, }, { testName: "queryCache should be empty when Request.URL is nil", testContext: &Context{Request: &http.Request{URL: nil}}, // explicit nil for readability expectedQueryCache: url.Values{}, }, { testName: "queryCache should be populated when it not yet populated and Request + Request.URL are non nil", testContext: &Context{Request: &http.Request{URL: validURL}}, // explicit nil for readability expectedQueryCache: url.Values{"key": []string{"value"}, "otherkey": []string{"othervalue"}}, }, } for _, test := range tests { t.Run(test.testName, func(t *testing.T) { test.testContext.initQueryCache() assert.Equal(t, test.expectedQueryCache, test.testContext.queryCache) }) } } func TestContextDefaultQueryOnEmptyRequest(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) // here c.Request == nil assert.NotPanics(t, func() { value, ok := c.GetQuery("NoKey") assert.False(t, ok) assert.Empty(t, value) }) assert.NotPanics(t, func() { assert.Equal(t, "nada", c.DefaultQuery("NoKey", "nada")) }) assert.NotPanics(t, func() { assert.Empty(t, c.Query("NoKey")) }) } func TestContextQueryAndPostForm(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) body := strings.NewReader("foo=bar&page=11&both=&foo=second") c.Request, _ = http.NewRequest(http.MethodPost, "/?both=GET&id=main&id=omit&array[]=first&array[]=second&ids[a]=hi&ids[b]=3.14", body) c.Request.Header.Add("Content-Type", MIMEPOSTForm) assert.Equal(t, "bar", c.DefaultPostForm("foo", "none")) assert.Equal(t, "bar", c.PostForm("foo")) assert.Empty(t, c.Query("foo")) value, ok := c.GetPostForm("page") assert.True(t, ok) assert.Equal(t, "11", value) assert.Equal(t, "11", c.DefaultPostForm("page", "0")) assert.Equal(t, "11", c.PostForm("page")) assert.Empty(t, c.Query("page")) value, ok = c.GetPostForm("both") assert.True(t, ok) assert.Empty(t, value) assert.Empty(t, c.PostForm("both")) assert.Empty(t, c.DefaultPostForm("both", "nothing")) assert.Equal(t, http.MethodGet, c.Query("both"), http.MethodGet) value, ok = c.GetQuery("id") assert.True(t, ok) assert.Equal(t, "main", value) assert.Equal(t, "000", c.DefaultPostForm("id", "000")) assert.Equal(t, "main", c.Query("id")) assert.Empty(t, c.PostForm("id")) value, ok = c.GetQuery("NoKey") assert.False(t, ok) assert.Empty(t, value) value, ok = c.GetPostForm("NoKey") assert.False(t, ok) assert.Empty(t, value) assert.Equal(t, "nada", c.DefaultPostForm("NoKey", "nada")) assert.Equal(t, "nothing", c.DefaultQuery("NoKey", "nothing")) assert.Empty(t, c.PostForm("NoKey")) assert.Empty(t, c.Query("NoKey")) var obj struct { Foo string `form:"foo"` ID string `form:"id"` Page int `form:"page"` Both string `form:"both"` Array []string `form:"array[]"` } require.NoError(t, c.Bind(&obj)) assert.Equal(t, "bar", obj.Foo, "bar") assert.Equal(t, "main", obj.ID, "main") assert.Equal(t, 11, obj.Page, 11) assert.Empty(t, obj.Both) assert.Equal(t, []string{"first", "second"}, obj.Array) values, ok := c.GetQueryArray("array[]") assert.True(t, ok) assert.Equal(t, "first", values[0]) assert.Equal(t, "second", values[1]) values = c.QueryArray("array[]") assert.Equal(t, "first", values[0]) assert.Equal(t, "second", values[1]) values = c.QueryArray("nokey") assert.Empty(t, values) values = c.QueryArray("both") assert.Len(t, values, 1) assert.Equal(t, http.MethodGet, values[0]) dicts, ok := c.GetQueryMap("ids") assert.True(t, ok) assert.Equal(t, "hi", dicts["a"]) assert.Equal(t, "3.14", dicts["b"]) dicts, ok = c.GetQueryMap("nokey") assert.False(t, ok) assert.Empty(t, dicts) dicts, ok = c.GetQueryMap("both") assert.False(t, ok) assert.Empty(t, dicts) dicts, ok = c.GetQueryMap("array") assert.False(t, ok) assert.Empty(t, dicts) dicts = c.QueryMap("ids") assert.Equal(t, "hi", dicts["a"]) assert.Equal(t, "3.14", dicts["b"]) dicts = c.QueryMap("nokey") assert.Empty(t, dicts) } func TestContextPostFormMultipart(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request = createMultipartRequest() var obj struct { Foo string `form:"foo"` Bar string `form:"bar"` BarAsInt int `form:"bar"` Array []string `form:"array"` ID string `form:"id"` TimeLocal time.Time `form:"time_local" time_format:"02/01/2006 15:04"` TimeUTC time.Time `form:"time_utc" time_format:"02/01/2006 15:04" time_utc:"1"` TimeLocation time.Time `form:"time_location" time_format:"02/01/2006 15:04" time_location:"Asia/Tokyo"` BlankTime time.Time `form:"blank_time" time_format:"02/01/2006 15:04"` } require.NoError(t, c.Bind(&obj)) assert.Equal(t, "bar", obj.Foo) assert.Equal(t, "10", obj.Bar) assert.Equal(t, 10, obj.BarAsInt) assert.Equal(t, []string{"first", "second"}, obj.Array) assert.Empty(t, obj.ID) assert.Equal(t, "31/12/2016 14:55", obj.TimeLocal.Format("02/01/2006 15:04")) assert.Equal(t, time.Local, obj.TimeLocal.Location()) assert.Equal(t, "31/12/2016 14:55", obj.TimeUTC.Format("02/01/2006 15:04")) assert.Equal(t, time.UTC, obj.TimeUTC.Location()) loc, _ := time.LoadLocation("Asia/Tokyo") assert.Equal(t, "31/12/2016 14:55", obj.TimeLocation.Format("02/01/2006 15:04")) assert.Equal(t, loc, obj.TimeLocation.Location()) assert.True(t, obj.BlankTime.IsZero()) value, ok := c.GetQuery("foo") assert.False(t, ok) assert.Empty(t, value) assert.Empty(t, c.Query("bar")) assert.Equal(t, "nothing", c.DefaultQuery("id", "nothing")) value, ok = c.GetPostForm("foo") assert.True(t, ok) assert.Equal(t, "bar", value) assert.Equal(t, "bar", c.PostForm("foo")) value, ok = c.GetPostForm("array") assert.True(t, ok) assert.Equal(t, "first", value) assert.Equal(t, "first", c.PostForm("array")) assert.Equal(t, "10", c.DefaultPostForm("bar", "nothing")) value, ok = c.GetPostForm("id") assert.True(t, ok) assert.Empty(t, value) assert.Empty(t, c.PostForm("id")) assert.Empty(t, c.DefaultPostForm("id", "nothing")) value, ok = c.GetPostForm("nokey") assert.False(t, ok) assert.Empty(t, value) assert.Equal(t, "nothing", c.DefaultPostForm("nokey", "nothing")) values, ok := c.GetPostFormArray("array") assert.True(t, ok) assert.Equal(t, "first", values[0]) assert.Equal(t, "second", values[1]) values = c.PostFormArray("array") assert.Equal(t, "first", values[0]) assert.Equal(t, "second", values[1]) values = c.PostFormArray("nokey") assert.Empty(t, values) values = c.PostFormArray("foo") assert.Len(t, values, 1) assert.Equal(t, "bar", values[0]) dicts, ok := c.GetPostFormMap("names") assert.True(t, ok) assert.Equal(t, "thinkerou", dicts["a"]) assert.Equal(t, "tianou", dicts["b"]) dicts, ok = c.GetPostFormMap("nokey") assert.False(t, ok) assert.Empty(t, dicts) dicts = c.PostFormMap("names") assert.Equal(t, "thinkerou", dicts["a"]) assert.Equal(t, "tianou", dicts["b"]) dicts = c.PostFormMap("nokey") assert.Empty(t, dicts) } func TestContextSetCookie(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.SetSameSite(http.SameSiteLaxMode) c.SetCookie("user", "gin", 1, "/", "localhost", true, true) assert.Equal(t, "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure; SameSite=Lax", c.Writer.Header().Get("Set-Cookie")) } func TestContextSetCookiePathEmpty(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.SetSameSite(http.SameSiteLaxMode) c.SetCookie("user", "gin", 1, "", "localhost", true, true) assert.Equal(t, "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure; SameSite=Lax", c.Writer.Header().Get("Set-Cookie")) } func TestContextGetCookie(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.Request, _ = http.NewRequest(http.MethodGet, "/get", nil) c.Request.Header.Set("Cookie", "user=gin") cookie, _ := c.Cookie("user") assert.Equal(t, "gin", cookie) _, err := c.Cookie("nokey") require.Error(t, err) } func TestContextBodyAllowedForStatus(t *testing.T) { assert.False(t, bodyAllowedForStatus(http.StatusProcessing)) assert.False(t, bodyAllowedForStatus(http.StatusNoContent)) assert.False(t, bodyAllowedForStatus(http.StatusNotModified)) assert.True(t, bodyAllowedForStatus(http.StatusInternalServerError)) } type TestRender struct{} func (*TestRender) Render(http.ResponseWriter) error { return errTestRender } func (*TestRender) WriteContentType(http.ResponseWriter) {} func TestContextRenderIfErr(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Render(http.StatusOK, &TestRender{}) assert.Equal(t, errorMsgs{&Error{Err: errTestRender, Type: 1}}, c.Errors) } // Tests that the response is serialized as JSON // and Content-Type is set to application/json // and special HTML characters are escaped func TestContextRenderJSON(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.JSON(http.StatusCreated, H{"foo": "bar", "html": "<b>"}) assert.Equal(t, http.StatusCreated, w.Code) assert.JSONEq(t, "{\"foo\":\"bar\",\"html\":\"\\u003cb\\u003e\"}", w.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type")) } // Tests that the response is serialized as JSONP // and Content-Type is set to application/javascript func TestContextRenderJSONP(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Request, _ = http.NewRequest(http.MethodGet, "http://example.com/?callback=x", nil) c.JSONP(http.StatusCreated, H{"foo": "bar"}) assert.Equal(t, http.StatusCreated, w.Code) assert.Equal(t, "x({\"foo\":\"bar\"});", w.Body.String()) assert.Equal(t, "application/javascript; charset=utf-8", w.Header().Get("Content-Type")) } // Tests that the response is serialized as JSONP // and Content-Type is set to application/json func TestContextRenderJSONPWithoutCallback(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.Request, _ = http.NewRequest(http.MethodGet, "http://example.com", nil) c.JSONP(http.StatusCreated, H{"foo": "bar"}) assert.Equal(t, http.StatusCreated, w.Code) assert.JSONEq(t, `{"foo":"bar"}`, w.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type")) } // Tests that no JSON is rendered if code is 204 func TestContextRenderNoContentJSON(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w) c.JSON(http.StatusNoContent, H{"foo": "bar"}) assert.Equal(t, http.StatusNoContent, w.Code) assert.Empty(t, w.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type")) } // Tests that the response is serialized as JSON // we change the content-type before func TestContextRenderAPIJSON(t *testing.T) { w := httptest.NewRecorder()
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
true
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/recovery_test.go
recovery_test.go
// 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 gin import ( "net" "net/http" "os" "strings" "syscall" "testing" "github.com/stretchr/testify/assert" ) func TestPanicClean(t *testing.T) { buffer := new(strings.Builder) router := New() password := "my-super-secret-password" router.Use(RecoveryWithWriter(buffer)) router.GET("/recovery", func(c *Context) { c.AbortWithStatus(http.StatusBadRequest) panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, http.MethodGet, "/recovery", header{ Key: "Host", Value: "www.google.com", }, header{ Key: "Authorization", Value: "Bearer " + password, }, header{ Key: "Content-Type", Value: "application/json", }, ) // TEST assert.Equal(t, http.StatusBadRequest, w.Code) // 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.Builder) router := New() router.Use(RecoveryWithWriter(buffer)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, http.MethodGet, "/recovery") // TEST assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, http.MethodGet, "/recovery") // TEST assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") SetMode(TestMode) } // TestPanicWithAbort assert that panic has been recovered even if context.Abort was used. func TestPanicWithAbort(t *testing.T) { router := New() router.Use(RecoveryWithWriter(nil)) router.GET("/recovery", func(c *Context) { c.AbortWithStatus(http.StatusBadRequest) panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, http.MethodGet, "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) } func TestFunction(t *testing.T) { bs := function(1) assert.Equal(t, dunno, bs) } // TestPanicWithBrokenPipe asserts that recovery specifically handles // writing responses to broken pipes func TestPanicWithBrokenPipe(t *testing.T) { const expectCode = 204 expectMsgs := map[syscall.Errno]string{ syscall.EPIPE: "broken pipe", syscall.ECONNRESET: "connection reset by peer", } for errno, expectMsg := range expectMsgs { t.Run(expectMsg, func(t *testing.T) { var buf strings.Builder router := New() router.Use(RecoveryWithWriter(&buf)) router.GET("/recovery", func(c *Context) { // Start writing response c.Header("X-Test", "Value") c.Status(expectCode) // Oops. Client connection closed e := &net.OpError{Err: &os.SyscallError{Err: errno}} panic(e) }) // RUN w := PerformRequest(router, http.MethodGet, "/recovery") // TEST assert.Equal(t, expectCode, w.Code) assert.Contains(t, strings.ToLower(buf.String()), expectMsg) }) } } // TestPanicWithAbortHandler asserts that recovery handles http.ErrAbortHandler as broken pipe func TestPanicWithAbortHandler(t *testing.T) { const expectCode = 204 var buf strings.Builder router := New() router.Use(RecoveryWithWriter(&buf)) router.GET("/recovery", func(c *Context) { // Start writing response c.Header("X-Test", "Value") c.Status(expectCode) // Panic with ErrAbortHandler which should be treated as broken pipe panic(http.ErrAbortHandler) }) // RUN w := PerformRequest(router, http.MethodGet, "/recovery") // TEST assert.Equal(t, expectCode, w.Code) out := buf.String() assert.Contains(t, out, "net/http: abort Handler") assert.NotContains(t, out, "panic recovered") } func TestCustomRecoveryWithWriter(t *testing.T) { errBuffer := new(strings.Builder) buffer := new(strings.Builder) router := New() handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(CustomRecoveryWithWriter(buffer, handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, http.MethodGet, "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, http.MethodGet, "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) } func TestCustomRecovery(t *testing.T) { errBuffer := new(strings.Builder) buffer := new(strings.Builder) router := New() DefaultErrorWriter = buffer handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(CustomRecovery(handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, http.MethodGet, "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, http.MethodGet, "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) } func TestRecoveryWithWriterWithCustomRecovery(t *testing.T) { errBuffer := new(strings.Builder) buffer := new(strings.Builder) router := New() DefaultErrorWriter = buffer handleRecovery := func(c *Context, err any) { errBuffer.WriteString(err.(string)) c.AbortWithStatus(http.StatusBadRequest) } router.Use(RecoveryWithWriter(DefaultErrorWriter, handleRecovery)) router.GET("/recovery", func(_ *Context) { panic("Oupps, Houston, we have a problem") }) // RUN w := PerformRequest(router, http.MethodGet, "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "panic recovered") assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem") assert.Contains(t, buffer.String(), t.Name()) assert.NotContains(t, buffer.String(), "GET /recovery") // Debug mode prints the request SetMode(DebugMode) // RUN w = PerformRequest(router, http.MethodGet, "/recovery") // TEST assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, buffer.String(), "GET /recovery") assert.Equal(t, strings.Repeat("Oupps, Houston, we have a problem", 2), errBuffer.String()) SetMode(TestMode) } func TestSecureRequestDump(t *testing.T) { tests := []struct { name string req *http.Request wantContains string wantNotContain string }{ { name: "Authorization header standard case", req: func() *http.Request { r, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) r.Header.Set("Authorization", "Bearer secret-token") return r }(), wantContains: "Authorization: *", wantNotContain: "Bearer secret-token", }, { name: "authorization header lowercase", req: func() *http.Request { r, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) r.Header.Set("authorization", "some-secret") return r }(), wantContains: "Authorization: *", wantNotContain: "some-secret", }, { name: "Authorization header mixed case", req: func() *http.Request { r, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) r.Header.Set("AuThOrIzAtIoN", "token123") return r }(), wantContains: "Authorization: *", wantNotContain: "token123", }, { name: "No Authorization header", req: func() *http.Request { r, _ := http.NewRequest(http.MethodGet, "http://example.com", nil) r.Header.Set("Content-Type", "application/json") return r }(), wantContains: "", wantNotContain: "Authorization: *", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := secureRequestDump(tt.req) if tt.wantContains != "" && !strings.Contains(result, tt.wantContains) { t.Errorf("maskHeaders() = %q, want contains %q", result, tt.wantContains) } if tt.wantNotContain != "" && strings.Contains(result, tt.wantNotContain) { t.Errorf("maskHeaders() = %q, want NOT contain %q", result, tt.wantNotContain) } }) } } // TestReadNthLine tests the readNthLine function with various scenarios. func TestReadNthLine(t *testing.T) { // Create a temporary test file testContent := "line 0 \n line 1 \nline 2 \nline 3 \nline 4" tempFile, err := os.CreateTemp("", "testfile*.txt") if err != nil { t.Fatal(err) } defer os.Remove(tempFile.Name()) // Write test content to the temporary file if _, err := tempFile.WriteString(testContent); err != nil { t.Fatal(err) } if err := tempFile.Close(); err != nil { t.Fatal(err) } // Test cases tests := []struct { name string lineNum int fileName string want string wantErr bool }{ {name: "Read first line", lineNum: 0, fileName: tempFile.Name(), want: "line 0", wantErr: false}, {name: "Read middle line", lineNum: 2, fileName: tempFile.Name(), want: "line 2", wantErr: false}, {name: "Read last line", lineNum: 4, fileName: tempFile.Name(), want: "line 4", wantErr: false}, {name: "Line number exceeds file length", lineNum: 10, fileName: tempFile.Name(), want: "", wantErr: false}, {name: "Negative line number", lineNum: -1, fileName: tempFile.Name(), want: "", wantErr: false}, {name: "Non-existent file", lineNum: 1, fileName: "/non/existent/file.txt", want: "", wantErr: true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := readNthLine(tt.fileName, tt.lineNum) assert.Equal(t, tt.wantErr, err != nil) assert.Equal(t, tt.want, got) }) } } func BenchmarkStack(b *testing.B) { b.ReportAllocs() for b.Loop() { _ = stack(stackSkip) } }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/utils.go
utils.go
// 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 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 address. const localhostIP = "127.0.0.1" // localhostIPv6 indicates the default localhost IPv6 address. const localhostIPv6 = "::1" // Bind is a helper function for given interface object and returns 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{}) `) } 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 http.HandlerFunc) HandlerFunc { return func(c *Context) { f(c.Writer, c.Request) } } // WrapH is a helper function for wrapping http.Handler and returns a Gin middleware. func WrapH(h http.Handler) HandlerFunc { return func(c *Context) { h.ServeHTTP(c.Writer, c.Request) } } // H is a shortcut for map[string]any type H map[string]any // MarshalXML allows type H to be used with xml.Marshal. func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error { start.Name = xml.Name{ Space: "", Local: "map", } if err := e.EncodeToken(start); err != nil { return err } for key, value := range h { elem := xml.StartElement{ Name: xml.Name{Space: "", Local: key}, Attr: []xml.Attr{}, } if err := e.EncodeElement(value, elem); err != nil { return err } } return e.EncodeToken(xml.EndElement{Name: start.Name}) } func assert1(guard bool, text string) { if !guard { panic(text) } } func filterFlags(content string) string { for i, char := range content { if char == ' ' || char == ';' { return content[:i] } } return content } func chooseData(custom, wildcard any) any { if custom != nil { return custom } if wildcard != nil { return wildcard } panic("negotiation config is invalid") } func parseAccept(acceptHeader string) []string { parts := strings.Split(acceptHeader, ",") out := make([]string, 0, len(parts)) for _, part := range parts { if i := strings.IndexByte(part, ';'); i > 0 { part = part[:i] } if part = strings.TrimSpace(part); part != "" { out = append(out, part) } } return out } func lastChar(str string) uint8 { if str == "" { panic("The length of the string can't be 0") } return str[len(str)-1] } func nameOfFunction(f any) string { return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name() } func joinPaths(absolutePath, relativePath string) string { if relativePath == "" { return absolutePath } finalPath := path.Join(absolutePath, relativePath) if lastChar(relativePath) == '/' && lastChar(finalPath) != '/' { return finalPath + "/" } return finalPath } func resolveAddress(addr []string) string { switch len(addr) { case 0: if port := os.Getenv("PORT"); port != "" { debugPrint("Environment variable PORT=\"%s\"", port) return ":" + port } debugPrint("Environment variable PORT is undefined. Using port :8080 by default") return ":8080" case 1: return addr[0] default: panic("too many parameters") } } // https://stackoverflow.com/questions/53069040/checking-a-string-contains-only-ascii-characters func isASCII(s string) bool { for i := 0; i < len(s); i++ { if s[i] > unicode.MaxASCII { return false } } return true } // safeInt8 converts int to int8 safely, capping at math.MaxInt8 func safeInt8(n int) int8 { if n > math.MaxInt8 { return math.MaxInt8 } return int8(n) } // safeUint16 converts int to uint16 safely, capping at math.MaxUint16 func safeUint16(n int) uint16 { if n > math.MaxUint16 { return math.MaxUint16 } return uint16(n) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/routergroup.go
routergroup.go
// 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 gin import ( "net/http" "path" "regexp" "strings" ) var ( // regEnLetter matches english letters for http method name regEnLetter = regexp.MustCompile("^[A-Z]+$") // anyMethods for RouterGroup Any method anyMethods = []string{ 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, ...HandlerFunc) *RouterGroup } // IRoutes defines all router handle interface. type IRoutes interface { Use(...HandlerFunc) IRoutes Handle(string, string, ...HandlerFunc) IRoutes Any(string, ...HandlerFunc) IRoutes GET(string, ...HandlerFunc) IRoutes POST(string, ...HandlerFunc) IRoutes DELETE(string, ...HandlerFunc) IRoutes PATCH(string, ...HandlerFunc) IRoutes PUT(string, ...HandlerFunc) IRoutes OPTIONS(string, ...HandlerFunc) 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.FileSystem) IRoutes } // RouterGroup is used internally to configure router, a RouterGroup is associated with // a prefix and an array of handlers (middleware). type RouterGroup struct { Handlers HandlersChain basePath string engine *Engine root bool } var _ IRouter = (*RouterGroup)(nil) // Use adds middleware to the group, see example code in GitHub. func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes { group.Handlers = append(group.Handlers, middleware...) return group.returnObj() } // Group creates a new router group. You should add all the routes that have common middlewares or the same path prefix. // For example, all the routes that use a common middleware for authorization could be grouped. func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup { return &RouterGroup{ Handlers: group.combineHandlers(handlers), basePath: group.calculateAbsolutePath(relativePath), engine: group.engine, } } // BasePath returns the base path of router group. // For example, if v := router.Group("/rest/n/v1/api"), v.BasePath() is "/rest/n/v1/api". func (group *RouterGroup) BasePath() string { return group.basePath } func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes { absolutePath := group.calculateAbsolutePath(relativePath) handlers = group.combineHandlers(handlers) group.engine.addRoute(httpMethod, absolutePath, handlers) return group.returnObj() } // Handle registers a new request handle and middleware with the given path and method. // The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes. // See the example code in GitHub. // // For GET, POST, PUT, PATCH and DELETE requests the respective shortcut // functions can be used. // // This function is intended for bulk loading and to allow the usage of less // frequently used, non-standardized or custom methods (e.g. for internal // communication with a proxy). func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes { if matched := regEnLetter.MatchString(httpMethod); !matched { panic("http method " + httpMethod + " is not valid") } return group.handle(httpMethod, relativePath, handlers) } // POST is a shortcut for router.Handle("POST", path, handlers). func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodPost, relativePath, handlers) } // GET is a shortcut for router.Handle("GET", path, handlers). func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodGet, relativePath, handlers) } // DELETE is a shortcut for router.Handle("DELETE", path, handlers). func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodDelete, relativePath, handlers) } // PATCH is a shortcut for router.Handle("PATCH", path, handlers). func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodPatch, relativePath, handlers) } // PUT is a shortcut for router.Handle("PUT", path, handlers). func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodPut, relativePath, handlers) } // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handlers). func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodOptions, relativePath, handlers) } // HEAD is a shortcut for router.Handle("HEAD", path, handlers). func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes { return group.handle(http.MethodHead, relativePath, handlers) } // Any registers a route that matches all the HTTP methods. // GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE. func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes { for _, method := range anyMethods { group.handle(method, relativePath, handlers) } return group.returnObj() } // Match registers a route that matches the specified methods that you declared. func (group *RouterGroup) Match(methods []string, relativePath string, handlers ...HandlerFunc) IRoutes { for _, method := range methods { group.handle(method, relativePath, handlers) } return group.returnObj() } // StaticFile registers a single route in order to serve a single file of the local filesystem. // router.StaticFile("favicon.ico", "./resources/favicon.ico") func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes { return group.staticFileHandler(relativePath, func(c *Context) { c.File(filepath) }) } // StaticFileFS works just like `StaticFile` but a custom `http.FileSystem` can be used instead.. // router.StaticFileFS("favicon.ico", "./resources/favicon.ico", Dir{".", false}) // Gin by default uses: gin.Dir() func (group *RouterGroup) StaticFileFS(relativePath, filepath string, fs http.FileSystem) IRoutes { return group.staticFileHandler(relativePath, func(c *Context) { c.FileFromFS(filepath, fs) }) } func (group *RouterGroup) staticFileHandler(relativePath string, handler HandlerFunc) IRoutes { if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") { panic("URL parameters can not be used when serving a static file") } group.GET(relativePath, handler) group.HEAD(relativePath, handler) return group.returnObj() } // Static serves files from the given file system root. // Internally a http.FileServer is used, therefore http.NotFound is used instead // of the Router's NotFound handler. // To use the operating system's file system implementation, // use : // // router.Static("/static", "/var/www") func (group *RouterGroup) Static(relativePath, root string) IRoutes { return group.StaticFS(relativePath, Dir(root, false)) } // StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead. // Gin by default uses: gin.Dir() func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes { if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") { panic("URL parameters can not be used when serving a static folder") } handler := group.createStaticHandler(relativePath, fs) urlPattern := path.Join(relativePath, "/*filepath") // Register GET and HEAD handlers group.GET(urlPattern, handler) group.HEAD(urlPattern, handler) return group.returnObj() } func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc { absolutePath := group.calculateAbsolutePath(relativePath) fileServer := http.StripPrefix(absolutePath, http.FileServer(fs)) return func(c *Context) { if _, noListing := fs.(*OnlyFilesFS); noListing { c.Writer.WriteHeader(http.StatusNotFound) } file := c.Param("filepath") // Check if file exists and/or if we have permission to access it f, err := fs.Open(file) if err != nil { c.Writer.WriteHeader(http.StatusNotFound) c.handlers = group.engine.noRoute // Reset index c.index = -1 return } f.Close() fileServer.ServeHTTP(c.Writer, c.Request) } } func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain { finalSize := len(group.Handlers) + len(handlers) assert1(finalSize < int(abortIndex), "too many handlers") mergedHandlers := make(HandlersChain, finalSize) copy(mergedHandlers, group.Handlers) copy(mergedHandlers[len(group.Handlers):], handlers) return mergedHandlers } func (group *RouterGroup) calculateAbsolutePath(relativePath string) string { return joinPaths(group.basePath, relativePath) } func (group *RouterGroup) returnObj() IRoutes { if group.root { return group.engine } return group }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/mode.go
mode.go
// 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 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 indicates gin mode is debug. DebugMode = "debug" // ReleaseMode indicates gin mode is release. ReleaseMode = "release" // TestMode indicates gin mode is test. TestMode = "test" ) const ( 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 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 io.Writer used by Gin to debug errors var DefaultErrorWriter io.Writer = os.Stderr var ( ginMode int32 = debugCode modeName atomic.Value ) func init() { mode := os.Getenv(EnvGinMode) SetMode(mode) } // SetMode sets gin mode according to input string. func SetMode(value string) { if value == "" { if flag.Lookup("test.v") != nil { value = TestMode } else { value = DebugMode } } switch value { case DebugMode: atomic.StoreInt32(&ginMode, debugCode) case ReleaseMode: atomic.StoreInt32(&ginMode, releaseCode) case TestMode: atomic.StoreInt32(&ginMode, testCode) default: panic("gin mode unknown: " + value + " (available mode: debug release test)") } modeName.Store(value) } // DisableBindValidation closes the default validator. func DisableBindValidation() { binding.Validator = nil } // EnableJsonDecoderUseNumber sets true for binding.EnableDecoderUseNumber to // call the UseNumber method on the JSON Decoder instance. func EnableJsonDecoderUseNumber() { binding.EnableDecoderUseNumber = true } // EnableJsonDecoderDisallowUnknownFields sets true for binding.EnableDecoderDisallowUnknownFields to // call the DisallowUnknownFields method on the JSON Decoder instance. func EnableJsonDecoderDisallowUnknownFields() { binding.EnableDecoderDisallowUnknownFields = true } // Mode returns current gin mode. func Mode() string { return modeName.Load().(string) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/context_file_test.go
context_file_test.go
package gin import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/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", nil) c.File(testFile) assert.Equal(t, http.StatusOK, w.Code) assert.Contains(t, w.Body.String(), "This is a test file") assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) } // TestContextFileNotFound tests serving 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.StatusNotFound, w.Code) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/path_test.go
path_test.go
// Copyright 2013 Julien Schmidt. All rights reserved. // Based on the path package, Copyright 2009 The 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 cleanTests = []cleanPathTest{ // Already clean {"/", "/"}, {"/abc", "/abc"}, {"/a/b/c", "/a/b/c"}, {"/abc/", "/abc/"}, {"/a/b/c/", "/a/b/c/"}, // missing root {"", "/"}, {"a/", "/a/"}, {"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"}, {"//abc", "/abc"}, {"///abc", "/abc"}, {"//abc//", "/abc/"}, // Remove . elements {".", "/"}, {"./", "/"}, {"/abc/./def", "/abc/def"}, {"/./abc/def", "/abc/def"}, {"/abc/.", "/abc/"}, // Remove .. elements {"..", "/"}, {"../", "/"}, {"../../", "/"}, {"../..", "/"}, {"../../abc", "/abc"}, {"/abc/def/ghi/../jkl", "/abc/def/jkl"}, {"/abc/def/../ghi/../jkl", "/abc/jkl"}, {"/abc/def/..", "/abc"}, {"/abc/def/../..", "/"}, {"/abc/def/../../..", "/"}, {"/abc/def/../../..", "/"}, {"/abc/def/../../../ghi/jkl/../../../mno", "/mno"}, // Combinations {"abc/./../def", "/def"}, {"abc//./../def", "/def"}, {"abc/../../././../def", "/def"}, } func TestPathClean(t *testing.T) { for _, test := range cleanTests { assert.Equal(t, test.result, cleanPath(test.path)) assert.Equal(t, test.result, cleanPath(test.result)) } } func TestPathCleanMallocs(t *testing.T) { if testing.Short() { t.Skip("skipping malloc count in short mode") } if runtime.GOMAXPROCS(0) > 1 { t.Skip("skipping malloc count; GOMAXPROCS>1") } for _, test := range cleanTests { allocs := testing.AllocsPerRun(100, func() { cleanPath(test.result) }) assert.InDelta(t, 0, allocs, 0.01) } } func BenchmarkPathClean(b *testing.B) { b.ReportAllocs() for b.Loop() { for _, test := range cleanTests { cleanPath(test.path) } } } func genLongPaths() (testPaths []cleanPathTest) { for i := 1; i <= 1234; i++ { ss := strings.Repeat("a", i) correctPath := "/" + ss testPaths = append(testPaths, cleanPathTest{ path: correctPath, result: correctPath, }, cleanPathTest{ path: ss, result: correctPath, }, cleanPathTest{ path: "//" + ss, result: correctPath, }, cleanPathTest{ path: "/" + ss + "/b/..", result: correctPath, }) } return } func TestPathCleanLong(t *testing.T) { cleanTests := genLongPaths() for _, test := range cleanTests { assert.Equal(t, test.result, cleanPath(test.path)) assert.Equal(t, test.result, cleanPath(test.result)) } } func BenchmarkPathCleanLong(b *testing.B) { cleanTests := genLongPaths() b.ReportAllocs() for b.Loop() { for _, test := range cleanTests { cleanPath(test.path) } } } func TestRemoveRepeatedChar(t *testing.T) { testCases := []struct { name string str string char byte want string }{ { name: "empty", str: "", char: 'a', want: "", }, { name: "noSlash", str: "abc", char: ',', want: "abc", }, { name: "withSlash", str: "/a/b/c/", char: '/', want: "/a/b/c/", }, { name: "withRepeatedSlashes", str: "/a//b///c////", char: '/', want: "/a/b/c/", }, { name: "threeSlashes", str: "///", char: '/', want: "/", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { res := removeRepeatedChar(tc.str, tc.char) assert.Equal(t, tc.want, res) }) } }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/context_appengine.go
context_appengine.go
// Copyright 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 appengine package gin func init() { defaultPlatform = PlatformGoogleAppEngine }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/debug_test.go
debug_test.go
// 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 gin import ( "errors" "fmt" "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) assert.False(t, IsDebugging()) } func TestDebugPrint(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) SetMode(ReleaseMode) debugPrint("DEBUG this!") SetMode(TestMode) 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 *testing.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) }) assert.Regexp(t, `^\[GIN-debug\] debug print func test: 123`, re) } func TestDebugPrintError(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintError(nil) debugPrintError(errors.New("this is an error")) SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] [ERROR] this is an error\n", re) } func TestDebugPrintRoutes(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintRoute(http.MethodGet, "/path/to/route/:param", HandlersChain{func(c *Context) {}, handlerNameTest}) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] GET /path/to/route/:param --> (.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest \(2 handlers\)\n$`, re) } func TestDebugPrintRouteFunc(t *testing.T) { DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) { fmt.Fprintf(DefaultWriter, "[GIN-debug] %-6s %-40s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers) } re := captureOutput(t, func() { SetMode(DebugMode) debugPrintRoute(http.MethodGet, "/path/to/route/:param1/:param2", HandlersChain{func(c *Context) {}, handlerNameTest}) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] GET /path/to/route/:param1/:param2 --> (.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest \(2 handlers\)\n$`, re) } func TestDebugPrintLoadTemplate(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) templ := template.Must(template.New("").Delims("{[{", "}]}").ParseGlob("./testdata/template/hello.tmpl")) debugPrintLoadTemplate(templ) SetMode(TestMode) }) assert.Regexp(t, `^\[GIN-debug\] Loaded HTML Templates \(2\): \n(\t- \n|\t- hello\.tmpl\n){2}\n`, re) } func TestDebugPrintWARNINGSetHTMLTemplate(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGSetHTMLTemplate() SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] [WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called\nat initialization. ie. before any route is registered or the router is listening in a socket:\n\n\trouter := gin.Default()\n\trouter.SetHTMLTemplate(template) // << good place\n\n", re) } func TestDebugPrintWARNINGDefault(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGDefault() SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\n\n", re) } func TestDebugPrintWARNINGDefaultWithUnsupportedVersion(t *testing.T) { runtimeVersion = "go1.23.12" re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGDefault() SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] [WARNING] Now Gin requires Go 1.24+.\n\n[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\n\n", re) } func TestDebugPrintWARNINGNew(t *testing.T) { re := captureOutput(t, func() { SetMode(DebugMode) debugPrintWARNINGNew() SetMode(TestMode) }) assert.Equal(t, "[GIN-debug] [WARNING] Running in \"debug\" mode. Switch to \"release\" mode in production.\n - using env:\texport GIN_MODE=release\n - using code:\tgin.SetMode(gin.ReleaseMode)\n\n", re) } func captureOutput(t *testing.T, f func()) string { reader, writer, err := os.Pipe() if err != nil { panic(err) } defaultWriter := DefaultWriter defaultErrorWriter := DefaultErrorWriter defer func() { DefaultWriter = defaultWriter DefaultErrorWriter = defaultErrorWriter log.SetOutput(os.Stderr) }() DefaultWriter = writer DefaultErrorWriter = writer log.SetOutput(writer) out := make(chan string) wg := new(sync.WaitGroup) wg.Add(1) go func() { var buf strings.Builder wg.Done() _, err := io.Copy(&buf, reader) assert.NoError(t, err) out <- buf.String() }() wg.Wait() f() writer.Close() return <-out } func TestGetMinVer(t *testing.T) { var m uint64 var e error _, e = getMinVer("go1") require.Error(t, e) m, e = getMinVer("go1.1") assert.Equal(t, uint64(1), m) require.NoError(t, e) m, e = getMinVer("go1.1.1") require.NoError(t, e) assert.Equal(t, uint64(1), m) _, e = getMinVer("go1.1.1.1") require.Error(t, e) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/logger_test.go
logger_test.go
// 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 gin import ( "errors" "fmt" "net/http" "strings" "testing" "time" "github.com/stretchr/testify/assert" ) func init() { SetMode(TestMode) } func TestLogger(t *testing.T) { buffer := new(strings.Builder) router := New() router.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.OPTIONS("/example", func(c *Context) {}) PerformRequest(router, http.MethodGet, "/example?a=100") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), http.MethodGet) 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 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.MethodPost) assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, http.MethodPut, "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), http.MethodPut) assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, http.MethodDelete, "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), http.MethodDelete) assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "PATCH", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PATCH") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "HEAD", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "HEAD") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "OPTIONS", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "OPTIONS") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, http.MethodGet, "/notfound") assert.Contains(t, buffer.String(), "404") assert.Contains(t, buffer.String(), http.MethodGet) assert.Contains(t, buffer.String(), "/notfound") } func TestLoggerWithConfig(t *testing.T) { buffer := new(strings.Builder) router := New() router.Use(LoggerWithConfig(LoggerConfig{Output: 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.OPTIONS("/example", func(c *Context) {}) PerformRequest(router, http.MethodGet, "/example?a=100") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), http.MethodGet) 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 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.MethodPost) assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, http.MethodPut, "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), http.MethodPut) assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, http.MethodDelete, "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), http.MethodDelete) assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "PATCH", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "PATCH") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "HEAD", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "HEAD") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, "OPTIONS", "/example") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), "OPTIONS") assert.Contains(t, buffer.String(), "/example") buffer.Reset() PerformRequest(router, http.MethodGet, "/notfound") assert.Contains(t, buffer.String(), "404") assert.Contains(t, buffer.String(), http.MethodGet) assert.Contains(t, buffer.String(), "/notfound") } func TestLoggerWithFormatter(t *testing.T) { buffer := new(strings.Builder) d := DefaultWriter DefaultWriter = buffer defer func() { DefaultWriter = d }() router := New() router.Use(LoggerWithFormatter(func(param LogFormatterParams) string { return fmt.Sprintf("[FORMATTER TEST] %v | %3d | %13v | %15s | %-7s %#v\n%s", param.TimeStamp.Format("2006/01/02 - 15:04:05"), param.StatusCode, param.Latency, param.ClientIP, param.Method, param.Path, param.ErrorMessage, ) })) router.GET("/example", func(c *Context) {}) PerformRequest(router, http.MethodGet, "/example?a=100") // output test assert.Contains(t, buffer.String(), "[FORMATTER TEST]") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), http.MethodGet) assert.Contains(t, buffer.String(), "/example") assert.Contains(t, buffer.String(), "a=100") } func TestLoggerWithConfigFormatting(t *testing.T) { var gotParam LogFormatterParams var gotKeys map[any]any buffer := new(strings.Builder) router := New() router.engine.trustedCIDRs, _ = router.engine.prepareTrustedCIDRs() router.Use(LoggerWithConfig(LoggerConfig{ Output: buffer, Formatter: func(param LogFormatterParams) string { // for assert test gotParam = param return fmt.Sprintf("[FORMATTER TEST] %v | %3d | %13v | %15s | %-7s %s\n%s", param.TimeStamp.Format("2006/01/02 - 15:04:05"), param.StatusCode, param.Latency, param.ClientIP, param.Method, param.Path, param.ErrorMessage, ) }, })) router.GET("/example", func(c *Context) { // set dummy ClientIP c.Request.Header.Set("X-Forwarded-For", "20.20.20.20") gotKeys = c.Keys time.Sleep(time.Millisecond) }) PerformRequest(router, http.MethodGet, "/example?a=100") // output test assert.Contains(t, buffer.String(), "[FORMATTER TEST]") assert.Contains(t, buffer.String(), "200") assert.Contains(t, buffer.String(), http.MethodGet) assert.Contains(t, buffer.String(), "/example") assert.Contains(t, buffer.String(), "a=100") // LogFormatterParams test assert.NotNil(t, gotParam.Request) assert.NotEmpty(t, gotParam.TimeStamp) assert.Equal(t, 200, gotParam.StatusCode) assert.NotEmpty(t, gotParam.Latency) assert.Equal(t, "20.20.20.20", gotParam.ClientIP) assert.Equal(t, http.MethodGet, gotParam.Method) assert.Equal(t, "/example?a=100", gotParam.Path) assert.Empty(t, gotParam.ErrorMessage) assert.Equal(t, gotKeys, gotParam.Keys) } func TestDefaultLogFormatter(t *testing.T) { timeStamp := time.Unix(1544173902, 0).UTC() termFalseParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Second * 5, ClientIP: "20.20.20.20", Method: http.MethodGet, Path: "/", ErrorMessage: "", isTerm: false, } termTrueParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Second * 5, ClientIP: "20.20.20.20", Method: http.MethodGet, Path: "/", ErrorMessage: "", isTerm: true, } termTrueLongDurationParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Millisecond * 9876543210, ClientIP: "20.20.20.20", Method: http.MethodGet, Path: "/", ErrorMessage: "", isTerm: true, } termFalseLongDurationParam := LogFormatterParams{ TimeStamp: timeStamp, StatusCode: 200, Latency: time.Millisecond * 9876543210, ClientIP: "20.20.20.20", Method: http.MethodGet, Path: "/", ErrorMessage: "", isTerm: false, } assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 | 200 | 5s | 20.20.20.20 | GET \"/\"\n", defaultLogFormatter(termFalseParam)) assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 | 200 | 2743h29m0s | 20.20.20.20 | GET \"/\"\n", defaultLogFormatter(termFalseLongDurationParam)) assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 |\x1b[97;42m 200 \x1b[0m|\x1b[97;41m 5s \x1b[0m| 20.20.20.20 |\x1b[97;44m GET \x1b[0m \"/\"\n", defaultLogFormatter(termTrueParam)) assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 |\x1b[97;42m 200 \x1b[0m|\x1b[97;41m 2743h29m0s \x1b[0m| 20.20.20.20 |\x1b[97;44m GET \x1b[0m \"/\"\n", defaultLogFormatter(termTrueLongDurationParam)) } func TestColorForMethod(t *testing.T) { colorForMethod := func(method string) string { p := LogFormatterParams{ Method: method, } return p.MethodColor() } assert.Equal(t, blue, colorForMethod(http.MethodGet), "get should be blue") assert.Equal(t, cyan, colorForMethod(http.MethodPost), "post should be cyan") assert.Equal(t, yellow, colorForMethod(http.MethodPut), "put should be yellow") assert.Equal(t, red, colorForMethod(http.MethodDelete), "delete should be red") assert.Equal(t, green, colorForMethod("PATCH"), "patch should be green") assert.Equal(t, magenta, colorForMethod("HEAD"), "head should be magenta") assert.Equal(t, white, colorForMethod("OPTIONS"), "options should be white") assert.Equal(t, reset, colorForMethod("TRACE"), "trace is not defined and should be the reset color") } func TestColorForStatus(t *testing.T) { colorForStatus := func(code int) string { p := LogFormatterParams{ StatusCode: code, } return p.StatusCodeColor() } assert.Equal(t, white, colorForStatus(http.StatusContinue), "1xx should be white") assert.Equal(t, green, colorForStatus(http.StatusOK), "2xx should be green") assert.Equal(t, white, colorForStatus(http.StatusMovedPermanently), "3xx should be white") assert.Equal(t, yellow, colorForStatus(http.StatusNotFound), "4xx should be yellow") assert.Equal(t, red, colorForStatus(2), "other things should be red") } func TestColorForLatency(t *testing.T) { colorForLantency := func(latency time.Duration) string { p := LogFormatterParams{ Latency: latency, } return p.LatencyColor() } assert.Equal(t, white, colorForLantency(time.Duration(0)), "0 should be white") assert.Equal(t, white, colorForLantency(time.Millisecond*20), "20ms should be white") assert.Equal(t, green, colorForLantency(time.Millisecond*150), "150ms should be green") assert.Equal(t, cyan, colorForLantency(time.Millisecond*250), "250ms should be cyan") assert.Equal(t, yellow, colorForLantency(time.Millisecond*600), "600ms should be yellow") assert.Equal(t, magenta, colorForLantency(time.Millisecond*1500), "1.5s should be magenta") assert.Equal(t, red, colorForLantency(time.Second*3), "other things should be red") } func TestResetColor(t *testing.T) { p := LogFormatterParams{} assert.Equal(t, string([]byte{27, 91, 48, 109}), p.ResetColor()) } func TestIsOutputColor(t *testing.T) { // test with isTerm flag true. p := LogFormatterParams{ isTerm: true, } consoleColorMode = autoColor assert.True(t, p.IsOutputColor()) ForceConsoleColor() assert.True(t, p.IsOutputColor()) DisableConsoleColor() assert.False(t, p.IsOutputColor()) // test with isTerm flag false. p = LogFormatterParams{ isTerm: false, } consoleColorMode = autoColor assert.False(t, p.IsOutputColor()) ForceConsoleColor() assert.True(t, p.IsOutputColor()) DisableConsoleColor() assert.False(t, p.IsOutputColor()) // reset console color mode. consoleColorMode = autoColor } func TestErrorLogger(t *testing.T) { router := New() router.Use(ErrorLogger()) router.GET("/error", func(c *Context) { c.Error(errors.New("this is an error")) //nolint: errcheck }) router.GET("/abort", func(c *Context) { c.AbortWithError(http.StatusUnauthorized, errors.New("no authorized")) //nolint: errcheck }) router.GET("/print", func(c *Context) { c.Error(errors.New("this is an error")) //nolint: errcheck c.String(http.StatusInternalServerError, "hola!") }) w := PerformRequest(router, http.MethodGet, "/error") assert.Equal(t, http.StatusOK, w.Code) assert.JSONEq(t, "{\"error\":\"this is an error\"}", w.Body.String()) w = PerformRequest(router, http.MethodGet, "/abort") assert.Equal(t, http.StatusUnauthorized, w.Code) assert.JSONEq(t, "{\"error\":\"no authorized\"}", w.Body.String()) w = PerformRequest(router, http.MethodGet, "/print") assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Equal(t, "hola!{\"error\":\"this is an error\"}", w.Body.String()) } func TestLoggerWithWriterSkippingPaths(t *testing.T) { buffer := new(strings.Builder) router := New() router.Use(LoggerWithWriter(buffer, "/skipped")) router.GET("/logged", func(c *Context) {}) router.GET("/skipped", func(c *Context) {}) PerformRequest(router, http.MethodGet, "/logged") assert.Contains(t, buffer.String(), "200") buffer.Reset() PerformRequest(router, http.MethodGet, "/skipped") assert.Contains(t, buffer.String(), "") } func TestLoggerWithConfigSkippingPaths(t *testing.T) { buffer := new(strings.Builder) router := New() router.Use(LoggerWithConfig(LoggerConfig{ Output: buffer, SkipPaths: []string{"/skipped"}, })) router.GET("/logged", func(c *Context) {}) router.GET("/skipped", func(c *Context) {}) PerformRequest(router, http.MethodGet, "/logged") assert.Contains(t, buffer.String(), "200") buffer.Reset() PerformRequest(router, http.MethodGet, "/skipped") assert.Contains(t, buffer.String(), "") } func TestLoggerWithConfigSkipper(t *testing.T) { buffer := new(strings.Builder) router := New() router.Use(LoggerWithConfig(LoggerConfig{ Output: buffer, Skip: func(c *Context) bool { return c.Writer.Status() == http.StatusNoContent }, })) router.GET("/logged", func(c *Context) { c.Status(http.StatusOK) }) router.GET("/skipped", func(c *Context) { c.Status(http.StatusNoContent) }) PerformRequest(router, http.MethodGet, "/logged") assert.Contains(t, buffer.String(), "200") buffer.Reset() PerformRequest(router, http.MethodGet, "/skipped") assert.Contains(t, buffer.String(), "") } func TestDisableConsoleColor(t *testing.T) { New() assert.Equal(t, autoColor, consoleColorMode) DisableConsoleColor() assert.Equal(t, disableColor, consoleColorMode) // reset console color mode. consoleColorMode = autoColor } func TestForceConsoleColor(t *testing.T) { New() assert.Equal(t, autoColor, consoleColorMode) ForceConsoleColor() assert.Equal(t, forceColor, consoleColorMode) // reset console color mode. consoleColorMode = autoColor }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/utils_test.go
utils_test.go
// 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 gin import ( "bytes" "encoding/xml" "fmt" "math" "net/http" "testing" "github.com/stretchr/testify/assert" ) func init() { SetMode(TestMode) } func BenchmarkParseAccept(b *testing.B) { for b.Loop() { parseAccept("text/html , application/xhtml+xml,application/xml;q=0.9, */* ;q=0.8") } } type testStruct struct { T *testing.T } func (t *testStruct) ServeHTTP(w http.ResponseWriter, 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 := New() 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) fmt.Fprint(w, "hola!") })) w := PerformRequest(router, http.MethodPost, "/path") assert.Equal(t, http.StatusInternalServerError, w.Code) assert.Equal(t, "hello", w.Body.String()) w = PerformRequest(router, http.MethodGet, "/path2") assert.Equal(t, http.StatusBadRequest, w.Code) assert.Equal(t, "hola!", w.Body.String()) } func TestLastChar(t *testing.T) { assert.Equal(t, uint8('a'), lastChar("hola")) assert.Equal(t, uint8('s'), lastChar("adios")) assert.Panics(t, func() { lastChar("") }) } func TestParseAccept(t *testing.T) { parts := parseAccept("text/html , application/xhtml+xml,application/xml;q=0.9, */* ;q=0.8") assert.Len(t, parts, 4) assert.Equal(t, "text/html", parts[0]) assert.Equal(t, "application/xhtml+xml", parts[1]) assert.Equal(t, "application/xml", parts[2]) assert.Equal(t, "*/*", parts[3]) } func TestChooseData(t *testing.T) { A := "a" B := "b" assert.Equal(t, A, chooseData(A, B)) assert.Equal(t, B, chooseData(nil, B)) assert.Panics(t, func() { chooseData(nil, nil) }) } func TestFilterFlags(t *testing.T) { result := filterFlags("text/html ") assert.Equal(t, "text/html", result) result = filterFlags("text/html;") assert.Equal(t, "text/html", result) } func TestFunctionName(t *testing.T) { assert.Regexp(t, `^(.*/vendor/)?github.com/gin-gonic/gin.somefunction$`, nameOfFunction(somefunction)) } func somefunction() { // this empty function is used by TestFunctionName() } func TestJoinPaths(t *testing.T) { assert.Empty(t, joinPaths("", "")) assert.Equal(t, "/", joinPaths("", "/")) assert.Equal(t, "/a", joinPaths("/a", "")) assert.Equal(t, "/a/", joinPaths("/a/", "")) assert.Equal(t, "/a/", joinPaths("/a/", "/")) assert.Equal(t, "/a/", joinPaths("/a", "/")) assert.Equal(t, "/a/hola", joinPaths("/a", "/hola")) assert.Equal(t, "/a/hola", joinPaths("/a/", "/hola")) assert.Equal(t, "/a/hola/", joinPaths("/a/", "/hola/")) assert.Equal(t, "/a/hola/", joinPaths("/a/", "/hola//")) } type bindTestStruct struct { Foo string `form:"foo" binding:"required"` Bar int `form:"bar" binding:"min=4"` } func TestBindMiddleware(t *testing.T) { var value *bindTestStruct var called bool router := New() router.GET("/", Bind(bindTestStruct{}), func(c *Context) { called = true value = c.MustGet(BindKey).(*bindTestStruct) }) PerformRequest(router, http.MethodGet, "/?foo=hola&bar=10") assert.True(t, called) assert.Equal(t, "hola", value.Foo) assert.Equal(t, 10, value.Bar) called = false PerformRequest(router, http.MethodGet, "/?foo=hola&bar=1") assert.False(t, called) assert.Panics(t, func() { Bind(&bindTestStruct{}) }) } func TestMarshalXMLforH(t *testing.T) { h := H{ "": "test", } var b bytes.Buffer enc := xml.NewEncoder(&b) var x xml.StartElement e := h.MarshalXML(enc, x) assert.Error(t, e) } func TestIsASCII(t *testing.T) { assert.True(t, isASCII("test")) assert.False(t, isASCII("πŸ§‘πŸ’›πŸ’šπŸ’™πŸ’œ")) } func TestSafeInt8(t *testing.T) { assert.Equal(t, int8(100), safeInt8(100)) assert.Equal(t, int8(math.MaxInt8), safeInt8(int(math.MaxInt8)+123)) } func TestSafeUint16(t *testing.T) { assert.Equal(t, uint16(100), safeUint16(100)) assert.Equal(t, uint16(math.MaxUint16), safeUint16(int(math.MaxUint16)+123)) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/debug.go
debug.go
// 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 gin import ( "fmt" "html/template" "runtime" "strconv" "strings" "sync/atomic" ) const ginSupportMinGoVer = 24 var runtimeVersion = runtime.Version() // IsDebugging returns true if the framework is running in debug mode. // Use SetMode(gin.ReleaseMode) to disable debug mode. func IsDebugging() bool { return atomic.LoadInt32(&ginMode) == debugCode } // DebugPrintRouteFunc indicates 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 ...any) func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) { if IsDebugging() { nuHandlers := len(handlers) handlerName := nameOfFunction(handlers.Last()) if DebugPrintRouteFunc == nil { debugPrint("%-6s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers) } else { DebugPrintRouteFunc(httpMethod, absolutePath, handlerName, nuHandlers) } } } func debugPrintLoadTemplate(tmpl *template.Template) { if IsDebugging() { var buf strings.Builder for _, tmpl := range tmpl.Templates() { buf.WriteString("\t- ") buf.WriteString(tmpl.Name()) buf.WriteString("\n") } debugPrint("Loaded HTML Templates (%d): \n%s\n", len(tmpl.Templates()), buf.String()) } } func debugPrint(format string, values ...any) { if !IsDebugging() { return } if DebugPrintFunc != nil { DebugPrintFunc(format, values...) return } if !strings.HasSuffix(format, "\n") { format += "\n" } fmt.Fprintf(DefaultWriter, "[GIN-debug] "+format, values...) } func getMinVer(v string) (uint64, error) { first := strings.IndexByte(v, '.') last := strings.LastIndexByte(v, '.') if first == last { return strconv.ParseUint(v[first+1:], 10, 64) } return strconv.ParseUint(v[first+1:last], 10, 64) } func debugPrintWARNINGDefault() { if v, e := getMinVer(runtimeVersion); e == nil && v < ginSupportMinGoVer { debugPrint(`[WARNING] Now Gin requires Go 1.24+. `) } debugPrint(`[WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached. `) } func debugPrintWARNINGNew() { debugPrint(`[WARNING] Running in "debug" mode. Switch to "release" mode in production. - using env: export GIN_MODE=release - using code: gin.SetMode(gin.ReleaseMode) `) } func debugPrintWARNINGSetHTMLTemplate() { debugPrint(`[WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called at initialization. ie. before any route is registered or the router is listening in a socket: router := gin.Default() router.SetHTMLTemplate(template) // << good place `) } func debugPrintError(err error) { if err != nil && IsDebugging() { fmt.Fprintf(DefaultErrorWriter, "[GIN-debug] [ERROR] %v\n", err) } }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/fs_test.go
fs_test.go
package gin 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 *testing.T) { var testFile *os.File mockFS := &mockFileSystem{ open: func(name string) (http.File, error) { return testFile, nil }, } fs := &OnlyFilesFS{FileSystem: mockFS} file, 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: 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) { n := neutralizedReaddirFile{} res, err := n.Readdir(0) require.NoError(t, err) assert.Nil(t, res) } func TestDir_listDirectory(t *testing.T) { testRoot := "foo" fs := Dir(testRoot, true) assert.Equal(t, http.Dir(testRoot), fs) } func TestDir(t *testing.T) { testRoot := "foo" fs := Dir(testRoot, false) assert.Equal(t, &OnlyFilesFS{FileSystem: http.Dir(testRoot)}, fs) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/benchmarks_test.go
benchmarks_test.go
// Copyright 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 ( "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 *testing.B) { router := New() router.Use(Recovery()) router.GET("/", func(c *Context) {}) runRequest(B, router, http.MethodGet, "/") } func BenchmarkLoggerMiddleware(B *testing.B) { router := 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(), LoggerWithWriter(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.Stdout router := New() router.Use(func(c *Context) {}) router.GET("/param/:param1/:params2/:param3/:param4/:param5", func(c *Context) {}) runRequest(B, router, http.MethodGet, "/param/path/to/parameter/john/12345") } func BenchmarkOneRouteJSON(B *testing.B) { router := New() data := struct { Status string `json:"status"` }{"ok"} router.GET("/json", func(c *Context) { c.JSON(http.StatusOK, data) }) runRequest(B, router, http.MethodGet, "/json") } func BenchmarkOneRouteHTML(B *testing.B) { router := New() t := template.Must(template.New("index").Parse(` <html><body><h1>{{.}}</h1></body></html>`)) router.SetHTMLTemplate(t) router.GET("/html", func(c *Context) { c.HTML(http.StatusOK, "index", "hola") }) runRequest(B, router, http.MethodGet, "/html") } func BenchmarkOneRouteSet(B *testing.B) { router := New() router.GET("/ping", func(c *Context) { c.Set("key", "value") }) runRequest(B, router, http.MethodGet, "/ping") } func BenchmarkOneRouteString(B *testing.B) { router := New() router.GET("/text", func(c *Context) { c.String(http.StatusOK, "this is a plain text") }) runRequest(B, router, http.MethodGet, "/text") } func BenchmarkManyRoutesFirst(B *testing.B) { router := New() router.Any("/ping", func(c *Context) {}) runRequest(B, router, http.MethodGet, "/ping") } func BenchmarkManyRoutesLast(B *testing.B) { router := New() router.Any("/ping", func(c *Context) {}) runRequest(B, router, "OPTIONS", "/ping") } func Benchmark404(B *testing.B) { router := New() router.Any("/something", func(c *Context) {}) router.NoRoute(func(c *Context) {}) runRequest(B, router, http.MethodGet, "/ping") } func Benchmark404Many(B *testing.B) { router := New() router.GET("/", func(c *Context) {}) router.GET("/path/to/something", func(c *Context) {}) router.GET("/post/:id", func(c *Context) {}) router.GET("/view/:id", func(c *Context) {}) router.GET("/favicon.ico", func(c *Context) {}) router.GET("/robots.txt", func(c *Context) {}) router.GET("/delete/:id", func(c *Context) {}) router.GET("/user/:id/:mode", func(c *Context) {}) router.NoRoute(func(c *Context) {}) runRequest(B, router, http.MethodGet, "/viewfake") } type mockWriter struct { headers http.Header } func newMockWriter() *mockWriter { return &mockWriter{ http.Header{}, } } func (m *mockWriter) Header() (h http.Header) { return m.headers } func (m *mockWriter) Write(p []byte) (n int, err error) { return len(p), nil } func (m *mockWriter) WriteString(s string) (n int, err error) { return len(s), nil } func (m *mockWriter) WriteHeader(int) {} func runRequest(B *testing.B, r *Engine, method, path string) { // create fake request req, err := http.NewRequest(method, path, nil) if err != nil { panic(err) } w := newMockWriter() B.ReportAllocs() B.ResetTimer() for i := 0; i < B.N; i++ { r.ServeHTTP(w, req) } }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/gin.go
gin.go
// 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 gin import ( "fmt" "html/template" "net" "net/http" "os" "path" "strings" "sync" "github.com/gin-gonic/gin/internal/bytesconv" filesystem "github.com/gin-gonic/gin/internal/fs" "github.com/gin-gonic/gin/render" "github.com/quic-go/quic-go/http3" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" ) const ( defaultMultipartMemory = 32 << 20 // 32 MB escapedColon = "\\:" colon = ":" backslash = "\\" ) var ( default404Body = []byte("404 page not found") default405Body = []byte("405 method not allowed") ) var defaultPlatform string var defaultTrustedCIDRs = []*net.IPNet{ { // 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}, }, } // HandlerFunc defines the handler used by gin middleware as return value. type HandlerFunc func(*Context) // OptionFunc defines the function to change the default configuration type OptionFunc 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 { 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 string HandlerFunc HandlerFunc } // RoutesInfo defines a RouteInfo slice. type RoutesInfo []RouteInfo // Trusted platforms const ( // PlatformGoogleAppEngine when running on Google App Engine. Trust X-Appengine-Remote-Addr // for determining the client's IP PlatformGoogleAppEngine = "X-Appengine-Remote-Addr" // PlatformCloudflare when using Cloudflare's CDN. Trust CF-Connecting-IP for determining // the client's IP PlatformCloudflare = "CF-Connecting-IP" // PlatformFlyIO when running on Fly.io. Trust Fly-Client-IP for determining the client's IP PlatformFlyIO = "Fly-Client-IP" ) // Engine is the framework's instance, it contains the muxer, middleware and configuration settings. // Create an instance of Engine, by using New() or Default() type Engine struct { RouterGroup // routeTreesUpdated ensures that the initialization or update of the route trees // (used for routing HTTP requests) happens only once, even if called multiple times concurrently. routeTreesUpdated sync.Once // RedirectTrailingSlash enables automatic redirection if the current route can't be matched but a // handler for the path with (without) the trailing slash exists. // For example if /foo/ is requested but a route only exists for /foo, the // client is redirected to /foo with http status code 301 for GET requests // and 307 for all other request methods. RedirectTrailingSlash bool // RedirectFixedPath if enabled, the router tries to fix the current request path, if no // handle is registered for it. // First superfluous path elements like ../ or // are removed. // Afterwards the router does a case-insensitive lookup of the cleaned path. // If a handle can be found for this route, the router makes a redirection // to the corrected path with status code 301 for GET requests and 307 for // all other request methods. // For example /FOO and /..//Foo could be redirected to /foo. // RedirectTrailingSlash is independent of this option. RedirectFixedPath bool // HandleMethodNotAllowed if enabled, the router checks if another method is allowed for the // current route, if the current request can not be routed. // If this is the case, the request is answered with 'Method Not Allowed' // and HTTP status code 405. // If no other Method is allowed, the request is delegated to the NotFound // handler. HandleMethodNotAllowed bool // ForwardedByClientIP if enabled, client IP will be parsed from the request's headers that // match those stored at `(*gin.Engine).RemoteIPHeaders`. If no IP was // fetched, it falls back to the IP obtained from // `(*gin.Context).Request.RemoteAddr`. ForwardedByClientIP bool // AppEngine was deprecated. // Deprecated: USE `TrustedPlatform` WITH VALUE `gin.PlatformGoogleAppEngine` INSTEAD // #726 #755 If enabled, it will trust some headers starting with // 'X-AppEngine...' for better integration with that PaaS. AppEngine bool // UseRawPath if enabled, the url.RawPath will be used to find parameters. // The RawPath is only a hint, EscapedPath() should be use instead. (https://pkg.go.dev/net/url@master#URL) // Only use RawPath if you know what you are doing. UseRawPath bool // UseEscapedPath if enable, the url.EscapedPath() will be used to find parameters // It overrides UseRawPath UseEscapedPath bool // UnescapePathValues if true, the path value will be unescaped. // If UseRawPath and UseEscapedPath are false (by default), the UnescapePathValues effectively is true, // as url.Path gonna be used, which is already unescaped. UnescapePathValues bool // RemoveExtraSlash a parameter can be parsed from the URL even with extra slashes. // See the PR #1817 and issue #1644 RemoveExtraSlash bool // RemoteIPHeaders list of headers used to obtain the client IP when // `(*gin.Engine).ForwardedByClientIP` is `true` and // `(*gin.Context).Request.RemoteAddr` is matched by at least one of the // network origins of list defined by `(*gin.Engine).SetTrustedProxies()`. RemoteIPHeaders []string // TrustedPlatform if set to a constant of value gin.Platform*, trusts the headers set by // that platform, for example to determine the client IP TrustedPlatform string // MaxMultipartMemory value of 'maxMemory' param that is given to http.Request's ParseMultipartForm // method call. MaxMultipartMemory int64 // UseH2C enable h2c support. UseH2C bool // ContextWithFallback enable fallback Context.Deadline(), Context.Done(), Context.Err() and Context.Value() when Context.Request.Context() is not nil. ContextWithFallback bool delims render.Delims secureJSONPrefix string HTMLRender render.HTMLRender FuncMap template.FuncMap allNoRoute HandlersChain allNoMethod HandlersChain noRoute HandlersChain noMethod HandlersChain pool sync.Pool trees methodTrees maxParams uint16 maxSections uint16 trustedProxies []string trustedCIDRs []*net.IPNet } var _ IRouter = (*Engine)(nil) // New returns a new blank Engine instance without any middleware attached. // By default, the configuration is: // - RedirectTrailingSlash: true // - RedirectFixedPath: false // - HandleMethodNotAllowed: false // - ForwardedByClientIP: true // - UseRawPath: false // - UseEscapedPath: false // - UnescapePathValues: true func New(opts ...OptionFunc) *Engine { debugPrintWARNINGNew() engine := &Engine{ RouterGroup: RouterGroup{ Handlers: nil, basePath: "/", root: true, }, FuncMap: template.FuncMap{}, RedirectTrailingSlash: true, RedirectFixedPath: false, HandleMethodNotAllowed: false, ForwardedByClientIP: true, RemoteIPHeaders: []string{"X-Forwarded-For", "X-Real-IP"}, TrustedPlatform: defaultPlatform, UseRawPath: false, UseEscapedPath: false, RemoveExtraSlash: false, UnescapePathValues: true, MaxMultipartMemory: defaultMultipartMemory, trees: make(methodTrees, 0, 9), delims: render.Delims{Left: "{{", Right: "}}"}, secureJSONPrefix: "while(1);", trustedProxies: []string{"0.0.0.0/0", "::/0"}, trustedCIDRs: defaultTrustedCIDRs, } engine.engine = engine engine.pool.New = func() any { return engine.allocateContext(engine.maxParams) } return engine.With(opts...) } // Default returns an Engine instance with the Logger and Recovery middleware already attached. func Default(opts ...OptionFunc) *Engine { debugPrintWARNINGDefault() engine := New() engine.Use(Logger(), Recovery()) return engine.With(opts...) } func (engine *Engine) Handler() http.Handler { if !engine.UseH2C { return engine } h2s := &http2.Server{} return h2c.NewHandler(engine, h2s) } func (engine *Engine) allocateContext(maxParams uint16) *Context { v := make(Params, 0, maxParams) skippedNodes := make([]skippedNode, 0, engine.maxSections) return &Context{engine: engine, params: &v, skippedNodes: &skippedNodes} } // Delims sets template left and right delims and returns an Engine instance. func (engine *Engine) Delims(left, right string) *Engine { engine.delims = render.Delims{Left: left, Right: right} return engine } // SecureJsonPrefix sets the secureJSONPrefix used in Context.SecureJSON. func (engine *Engine) SecureJsonPrefix(prefix string) *Engine { engine.secureJSONPrefix = prefix return engine } // LoadHTMLGlob loads HTML files identified by glob pattern // and associates the result with HTML renderer. func (engine *Engine) LoadHTMLGlob(pattern string) { left := engine.delims.Left right := engine.delims.Right templ := template.Must(template.New("").Delims(left, right).Funcs(engine.FuncMap).ParseGlob(pattern)) if IsDebugging() { debugPrintLoadTemplate(templ) engine.HTMLRender = render.HTMLDebug{Glob: pattern, FuncMap: engine.FuncMap, Delims: engine.delims} return } engine.SetHTMLTemplate(templ) } // LoadHTMLFiles loads a slice of HTML files // and associates the result with HTML renderer. func (engine *Engine) LoadHTMLFiles(files ...string) { if IsDebugging() { engine.HTMLRender = render.HTMLDebug{Files: files, FuncMap: engine.FuncMap, Delims: engine.delims} return } templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFiles(files...)) engine.SetHTMLTemplate(templ) } // LoadHTMLFS loads an http.FileSystem and a slice of patterns // and associates the result with HTML renderer. func (engine *Engine) LoadHTMLFS(fs http.FileSystem, patterns ...string) { if IsDebugging() { engine.HTMLRender = render.HTMLDebug{FileSystem: fs, Patterns: patterns, FuncMap: engine.FuncMap, Delims: engine.delims} return } templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFS( filesystem.FileSystem{FileSystem: fs}, patterns...)) engine.SetHTMLTemplate(templ) } // SetHTMLTemplate associate a template with HTML renderer. func (engine *Engine) SetHTMLTemplate(templ *template.Template) { if len(engine.trees) > 0 { debugPrintWARNINGSetHTMLTemplate() } engine.HTMLRender = render.HTMLProduction{Template: templ.Funcs(engine.FuncMap)} } // SetFuncMap sets the FuncMap used for template.FuncMap. func (engine *Engine) SetFuncMap(funcMap template.FuncMap) { engine.FuncMap = funcMap } // NoRoute adds handlers for NoRoute. It returns a 404 code by default. func (engine *Engine) NoRoute(handlers ...HandlerFunc) { engine.noRoute = handlers engine.rebuild404Handlers() } // NoMethod sets the handlers called when Engine.HandleMethodNotAllowed = true. func (engine *Engine) NoMethod(handlers ...HandlerFunc) { engine.noMethod = handlers engine.rebuild405Handlers() } // Use attaches a global middleware to the router. i.e. the middleware attached through Use() will be // included in the handlers chain for every single request. Even 404, 405, static files... // For example, this is the right place for a logger or error management middleware. func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes { engine.RouterGroup.Use(middleware...) engine.rebuild404Handlers() engine.rebuild405Handlers() return engine } // With returns an Engine with the configuration set in the OptionFunc. func (engine *Engine) With(opts ...OptionFunc) *Engine { for _, opt := range opts { opt(engine) } return engine } func (engine *Engine) rebuild404Handlers() { engine.allNoRoute = engine.combineHandlers(engine.noRoute) } func (engine *Engine) rebuild405Handlers() { engine.allNoMethod = engine.combineHandlers(engine.noMethod) } func (engine *Engine) addRoute(method, path string, handlers HandlersChain) { assert1(path[0] == '/', "path must begin with '/'") assert1(method != "", "HTTP method can not be empty") assert1(len(handlers) > 0, "there must be at least one handler") debugPrintRoute(method, path, handlers) root := engine.trees.get(method) if root == nil { root = new(node) root.fullPath = "/" engine.trees = append(engine.trees, methodTree{method: method, root: root}) } root.addRoute(path, handlers) if paramsCount := countParams(path); paramsCount > engine.maxParams { engine.maxParams = paramsCount } if sectionsCount := countSections(path); sectionsCount > engine.maxSections { engine.maxSections = sectionsCount } } // Routes returns a slice of registered routes, including some useful information, such as: // the http method, path, and the handler name. func (engine *Engine) Routes() (routes RoutesInfo) { for _, tree := range engine.trees { routes = iterate("", tree.method, routes, tree.root) } return routes } func iterate(path, method string, routes RoutesInfo, root *node) RoutesInfo { path += root.path if len(root.handlers) > 0 { handlerFunc := root.handlers.Last() routes = append(routes, RouteInfo{ Method: method, Path: path, Handler: nameOfFunction(handlerFunc), HandlerFunc: handlerFunc, }) } for _, child := range root.children { routes = iterate(path, method, routes, child) } return routes } func (engine *Engine) prepareTrustedCIDRs() ([]*net.IPNet, error) { if engine.trustedProxies == nil { return nil, nil } cidr := make([]*net.IPNet, 0, len(engine.trustedProxies)) for _, trustedProxy := range engine.trustedProxies { if !strings.Contains(trustedProxy, "/") { ip := parseIP(trustedProxy) if ip == nil { return cidr, &net.ParseError{Type: "IP address", Text: trustedProxy} } switch len(ip) { case net.IPv4len: trustedProxy += "/32" case net.IPv6len: trustedProxy += "/128" } } _, cidrNet, err := net.ParseCIDR(trustedProxy) if err != nil { return cidr, err } cidr = append(cidr, cidrNet) } return cidr, nil } // SetTrustedProxies set a list of network origins (IPv4 addresses, // IPv4 CIDRs, IPv6 addresses or IPv6 CIDRs) from which to trust // request's headers that contain alternative client IP when // `(*gin.Engine).ForwardedByClientIP` is `true`. `TrustedProxies` // feature is enabled by default, and it also trusts all proxies // by default. If you want to disable this feature, use // Engine.SetTrustedProxies(nil), then Context.ClientIP() will // return the remote address directly. func (engine *Engine) SetTrustedProxies(trustedProxies []string) error { engine.trustedProxies = trustedProxies return engine.parseTrustedProxies() } // isUnsafeTrustedProxies checks if Engine.trustedCIDRs contains all IPs, it's not safe if it has (returns true) func (engine *Engine) isUnsafeTrustedProxies() bool { return engine.isTrustedProxy(net.ParseIP("0.0.0.0")) || engine.isTrustedProxy(net.ParseIP("::")) } // parseTrustedProxies parse Engine.trustedProxies to Engine.trustedCIDRs func (engine *Engine) parseTrustedProxies() error { trustedCIDRs, err := engine.prepareTrustedCIDRs() engine.trustedCIDRs = trustedCIDRs return err } // isTrustedProxy will check whether the IP address is included in the trusted list according to Engine.trustedCIDRs func (engine *Engine) isTrustedProxy(ip net.IP) bool { if engine.trustedCIDRs == nil { return false } for _, cidr := range engine.trustedCIDRs { if cidr.Contains(ip) { return true } } return false } // validateHeader will parse X-Forwarded-For header and return the trusted client IP address func (engine *Engine) validateHeader(header string) (clientIP string, valid bool) { if header == "" { return "", false } items := strings.Split(header, ",") for i := len(items) - 1; i >= 0; i-- { ipStr := strings.TrimSpace(items[i]) ip := net.ParseIP(ipStr) if ip == nil { break } // X-Forwarded-For is appended by proxy // Check IPs in reverse order and stop when find untrusted proxy if (i == 0) || (!engine.isTrustedProxy(ip)) { return ipStr, true } } return "", false } // updateRouteTree do update to the route tree recursively func updateRouteTree(n *node) { n.path = strings.ReplaceAll(n.path, escapedColon, colon) n.fullPath = strings.ReplaceAll(n.fullPath, escapedColon, colon) n.indices = strings.ReplaceAll(n.indices, backslash, colon) if n.children == nil { return } for _, child := range n.children { updateRouteTree(child) } } // updateRouteTrees do update to the route trees func (engine *Engine) updateRouteTrees() { for _, tree := range engine.trees { updateRouteTree(tree.root) } } // parseIP parse a string representation of an IP and returns a net.IP with the // minimum byte representation or nil if input is invalid. func parseIP(ip string) net.IP { parsedIP := net.ParseIP(ip) if ipv4 := parsedIP.To4(); ipv4 != nil { // return ip in a 4-byte representation return ipv4 } // return ip in a 16-byte representation or nil return parsedIP } // Run attaches the router to a http.Server and starts listening and serving HTTP requests. // It is a shortcut for http.ListenAndServe(addr, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) Run(addr ...string) (err error) { defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.") } engine.updateRouteTrees() address := resolveAddress(addr) debugPrint("Listening and serving HTTP on %s\n", address) server := &http.Server{ // #nosec G112 Addr: address, Handler: engine.Handler(), } err = server.ListenAndServe() return } // RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests. // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error) { debugPrint("Listening and serving HTTPS on %s\n", addr) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.") } server := &http.Server{ // #nosec G112 Addr: addr, Handler: engine.Handler(), } err = server.ListenAndServeTLS(certFile, keyFile) return } // RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified unix socket (i.e. a file). // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunUnix(file string) (err error) { debugPrint("Listening and serving HTTP on unix:/%s", file) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.") } listener, err := net.Listen("unix", file) if err != nil { return } defer listener.Close() defer os.Remove(file) server := &http.Server{ // #nosec G112 Handler: engine.Handler(), } err = server.Serve(listener) return } // RunFd attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified file descriptor. // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunFd(fd int) (err error) { debugPrint("Listening and serving HTTP on fd@%d", fd) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.") } f := os.NewFile(uintptr(fd), fmt.Sprintf("fd@%d", fd)) defer f.Close() listener, err := net.FileListener(f) if err != nil { return } defer listener.Close() err = engine.RunListener(listener) return } // RunQUIC attaches the router to a http.Server and starts listening and serving QUIC requests. // It is a shortcut for http3.ListenAndServeQUIC(addr, certFile, keyFile, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func (engine *Engine) RunQUIC(addr, certFile, keyFile string) (err error) { debugPrint("Listening and serving QUIC on %s\n", addr) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.") } err = http3.ListenAndServeQUIC(addr, certFile, keyFile, engine.Handler()) return } // RunListener attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified net.Listener func (engine *Engine) RunListener(listener net.Listener) (err error) { debugPrint("Listening and serving HTTP on listener what's bind with address@%s", listener.Addr()) defer func() { debugPrintError(err) }() if engine.isUnsafeTrustedProxies() { debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" + "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.") } server := &http.Server{ // #nosec G112 Handler: engine.Handler(), } err = server.Serve(listener) return } // ServeHTTP conforms to the http.Handler interface. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) { engine.routeTreesUpdated.Do(func() { engine.updateRouteTrees() }) c := engine.pool.Get().(*Context) c.writermem.reset(w) c.Request = req c.reset() engine.handleHTTPRequest(c) engine.pool.Put(c) } // HandleContext re-enters a context that has been rewritten. // This can be done by setting c.Request.URL.Path to your new target. // Disclaimer: You can loop yourself to deal with this, use wisely. func (engine *Engine) HandleContext(c *Context) { oldIndexValue := c.index oldHandlers := c.handlers c.reset() engine.handleHTTPRequest(c) c.index = oldIndexValue c.handlers = oldHandlers } func (engine *Engine) handleHTTPRequest(c *Context) { httpMethod := c.Request.Method rPath := c.Request.URL.Path unescape := false if engine.UseEscapedPath { rPath = c.Request.URL.EscapedPath() unescape = engine.UnescapePathValues } else if engine.UseRawPath && len(c.Request.URL.RawPath) > 0 { rPath = c.Request.URL.RawPath unescape = engine.UnescapePathValues } if engine.RemoveExtraSlash { rPath = cleanPath(rPath) } // Find root of the tree for the given HTTP method t := engine.trees for i, tl := 0, len(t); i < tl; i++ { if t[i].method != httpMethod { continue } root := t[i].root // Find route in tree value := root.getValue(rPath, c.params, c.skippedNodes, unescape) if value.params != nil { c.Params = *value.params } if value.handlers != nil { c.handlers = value.handlers c.fullPath = value.fullPath c.Next() c.writermem.WriteHeaderNow() return } if httpMethod != http.MethodConnect && rPath != "/" { if value.tsr && engine.RedirectTrailingSlash { redirectTrailingSlash(c) return } if engine.RedirectFixedPath && redirectFixedPath(c, root, engine.RedirectFixedPath) { return } } break } if engine.HandleMethodNotAllowed && len(t) > 0 { // According to RFC 7231 section 6.5.5, MUST generate an Allow header field in response // containing a list of the target resource's currently supported methods. allowed := make([]string, 0, len(t)-1) for _, tree := range engine.trees { if tree.method == httpMethod { continue } if value := tree.root.getValue(rPath, nil, c.skippedNodes, unescape); value.handlers != nil { allowed = append(allowed, tree.method) } } if len(allowed) > 0 { c.handlers = engine.allNoMethod c.writermem.Header().Set("Allow", strings.Join(allowed, ", ")) serveError(c, http.StatusMethodNotAllowed, default405Body) return } } c.handlers = engine.allNoRoute serveError(c, http.StatusNotFound, default404Body) } var mimePlain = []string{MIMEPlain} func serveError(c *Context, code int, defaultMessage []byte) { c.writermem.status = code c.Next() if c.writermem.Written() { return } if c.writermem.Status() == code { c.writermem.Header()["Content-Type"] = mimePlain _, err := c.Writer.Write(defaultMessage) if err != nil { debugPrint("cannot write message to writer during serve error: %v", err) } return } c.writermem.WriteHeaderNow() } func redirectTrailingSlash(c *Context) { req := c.Request p := req.URL.Path if prefix := path.Clean(c.Request.Header.Get("X-Forwarded-Prefix")); prefix != "." { prefix = sanitizePathChars(prefix) prefix = removeRepeatedChar(prefix, '/') p = prefix + "/" + req.URL.Path } req.URL.Path = p + "/" if length := len(p); length > 1 && p[length-1] == '/' { req.URL.Path = p[:length-1] } redirectRequest(c) } // sanitizePathChars removes unsafe characters from path strings, // keeping only ASCII letters, ASCII numbers, forward slashes, and hyphens. func sanitizePathChars(s string) string { return strings.Map(func(r rune) rune { if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '/' || r == '-' { return r } return -1 }, s) } func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool { req := c.Request rPath := req.URL.Path if fixedPath, ok := root.findCaseInsensitivePath(cleanPath(rPath), trailingSlash); ok { req.URL.Path = bytesconv.BytesToString(fixedPath) redirectRequest(c) return true } return false } func redirectRequest(c *Context) { req := c.Request rPath := req.URL.Path rURL := req.URL.String() code := http.StatusMovedPermanently // Permanent redirect, request with GET method if req.Method != http.MethodGet { code = http.StatusTemporaryRedirect } debugPrint("redirecting request %d: %s --> %s", code, rPath, rURL) http.Redirect(c.Writer, req, rURL, code) c.writermem.WriteHeaderNow() }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/auth.go
auth.go
// 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 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 cookie name for proxy_user credential in basic auth for proxy. const AuthProxyUserKey = "proxy_user" // Accounts defines a key/value for user/pass list of authorized logins. type Accounts map[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 := 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 arguments a map[string]string where // the key is the user name and the value is the password, as well as the name of the Realm. // If the realm is empty, "Authorization Required" will be used by default. // (see http://tools.ietf.org/html/rfc2617#section-1.2) func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc { if realm == "" { realm = "Authorization Required" } realm = "Basic realm=" + strconv.Quote(realm) pairs := processAccounts(accounts) return func(c *Context) { // Search user in the slice of allowed credentials user, found := pairs.searchCredential(c.requestHeader("Authorization")) if !found { // Credentials doesn't match, we return 401 and abort handlers chain. c.Header("WWW-Authenticate", realm) c.AbortWithStatus(http.StatusUnauthorized) return } // The user credentials was found, set user's id to key AuthUserKey in this context, the user's id can be read later using // c.MustGet(gin.AuthUserKey). c.Set(AuthUserKey, user) } } // BasicAuth returns a Basic HTTP Authorization middleware. It takes as argument a map[string]string where // the key is the user name and the value is the password. func BasicAuth(accounts Accounts) HandlerFunc { return BasicAuthForRealm(accounts, "") } func processAccounts(accounts Accounts) authPairs { length := len(accounts) assert1(length > 0, "Empty list of authorized credentials") pairs := make(authPairs, 0, length) for user, password := range accounts { assert1(user != "", "User can not be empty") value := authorizationHeader(user, password) pairs = append(pairs, authPair{ value: value, user: user, }) } return pairs } func authorizationHeader(user, password string) string { base := user + ":" + password return "Basic " + base64.StdEncoding.EncodeToString(bytesconv.StringToBytes(base)) } // BasicAuthForProxy returns a Basic HTTP Proxy-Authorization middleware. // If the realm is empty, "Proxy Authorization Required" will be used by default. func BasicAuthForProxy(accounts Accounts, realm string) HandlerFunc { if realm == "" { realm = "Proxy Authorization Required" } realm = "Basic realm=" + strconv.Quote(realm) pairs := processAccounts(accounts) return func(c *Context) { proxyUser, found := pairs.searchCredential(c.requestHeader("Proxy-Authorization")) if !found { // Credentials doesn't match, we return 407 and abort handlers chain. c.Header("Proxy-Authenticate", realm) c.AbortWithStatus(http.StatusProxyAuthRequired) return } // The proxy_user credentials was found, set proxy_user's id to key AuthProxyUserKey in this context, the proxy_user's id can be read later using // c.MustGet(gin.AuthProxyUserKey). c.Set(AuthProxyUserKey, proxyUser) } }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/context.go
context.go
// 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 gin import ( "errors" "fmt" "io" "io/fs" "log" "maps" "math" "mime/multipart" "net" "net/http" "net/url" "os" "path/filepath" "strings" "sync" "time" "github.com/gin-contrib/sse" "github.com/gin-gonic/gin/binding" "github.com/gin-gonic/gin/render" ) // Content-Type MIME of the most common data formats. const ( MIMEJSON = binding.MIMEJSON MIMEHTML = binding.MIMEHTML MIMEXML = binding.MIMEXML MIMEXML2 = binding.MIMEXML2 MIMEPlain = binding.MIMEPlain MIMEPOSTForm = binding.MIMEPOSTForm MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm MIMEYAML = binding.MIMEYAML MIMEYAML2 = binding.MIMEYAML2 MIMETOML = binding.MIMETOML MIMEPROTOBUF = binding.MIMEPROTOBUF ) // BodyBytesKey indicates a default body bytes key. const BodyBytesKey = "_gin-gonic/gin/bodybyteskey" // ContextKey is the key that a Context returns itself for. const ContextKey = "_gin-gonic/gin/contextkey" type ContextKeyType int const ContextRequestKey ContextKeyType = 0 // abortIndex represents a typical value used in abort functions. const abortIndex int8 = math.MaxInt8 >> 1 // Context is the most important part of gin. It allows us to pass variables between middleware, // manage the flow, validate the JSON of a request and render a JSON response for example. type Context struct { 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 for the context of each request. Keys map[any]any // Errors is a list of errors attached to all the handlers/middlewares who used this context. Errors errorMsgs // Accepted defines a list 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 parsed 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 } /************************************/ /********** CONTEXT CREATION ********/ /************************************/ func (c *Context) reset() { c.Writer = &c.writermem c.Params = c.Params[:0] c.handlers = nil c.index = -1 c.fullPath = "" c.Keys = nil c.Errors = c.Errors[:0] c.Accepted = nil c.queryCache = nil c.formCache = nil c.sameSite = 0 *c.params = (*c.params)[:0] *c.skippedNodes = (*c.skippedNodes)[:0] } // Copy returns a copy of the current context that can be safely used outside the request's scope. // This has to be used when the context has to be passed to a goroutine. func (c *Context) Copy() *Context { cp := Context{ writermem: c.writermem, Request: c.Request, engine: c.engine, } cp.writermem.ResponseWriter = nil cp.Writer = &cp.writermem cp.index = abortIndex cp.handlers = nil cp.fullPath = c.fullPath cKeys := c.Keys c.mu.RLock() cp.Keys = maps.Clone(cKeys) c.mu.RUnlock() cParams := c.Params cp.Params = make([]Param, len(cParams)) copy(cp.Params, cParams) return &cp } // HandlerName returns the main handler's name. For example if the handler is "handleGetUsers()", // this function will return "main.handleGetUsers". func (c *Context) HandlerName() string { return nameOfFunction(c.handlers.Last()) } // HandlerNames returns a list of all registered handlers for this context in descending order, // following the semantics of HandlerName() func (c *Context) HandlerNames() []string { hn := make([]string, 0, len(c.handlers)) for _, val := range c.handlers { if val == nil { continue } hn = append(hn, nameOfFunction(val)) } return hn } // Handler returns the main handler. func (c *Context) Handler() HandlerFunc { return c.handlers.Last() } // FullPath returns a matched route full path. For not found routes // returns an empty string. // // router.GET("/user/:id", func(c *gin.Context) { // c.FullPath() == "/user/:id" // true // }) func (c *Context) FullPath() string { return c.fullPath } /************************************/ /*********** FLOW CONTROL ***********/ /************************************/ // Next should be used only inside middleware. // It executes the pending handlers in the chain inside the calling handler. // See example in GitHub. func (c *Context) Next() { c.index++ for c.index < safeInt8(len(c.handlers)) { if c.handlers[c.index] != nil { c.handlers[c.index](c) } c.index++ } } // IsAborted returns true if the current context was aborted. func (c *Context) IsAborted() bool { return c.index >= abortIndex } // Abort prevents pending handlers from being called. Note that this will not stop the current handler. // Let's say you have an authorization middleware that validates that the current request is authorized. // If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers // for this request are not called. func (c *Context) Abort() { c.index = abortIndex } // AbortWithStatus calls `Abort()` and writes the headers with the specified status code. // For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401). func (c *Context) AbortWithStatus(code int) { c.Status(code) c.Writer.WriteHeaderNow() c.Abort() } // AbortWithStatusPureJSON calls `Abort()` and then `PureJSON` internally. // This method stops the chain, writes the status code and return a JSON body without escaping. // It also sets the Content-Type as "application/json". func (c *Context) AbortWithStatusPureJSON(code int, jsonObj any) { c.Abort() c.PureJSON(code, jsonObj) } // AbortWithStatusJSON calls `Abort()` and then `JSON` internally. // This method stops the chain, writes the status code and return a JSON body. // It also sets the Content-Type as "application/json". func (c *Context) AbortWithStatusJSON(code int, jsonObj any) { c.Abort() c.JSON(code, jsonObj) } // AbortWithError calls `AbortWithStatus()` and `Error()` internally. // This method stops the chain, writes the status code and pushes the specified error to `c.Errors`. // See Context.Error() for more details. func (c *Context) AbortWithError(code int, err error) *Error { c.AbortWithStatus(code) return c.Error(err) } /************************************/ /********* ERROR MANAGEMENT *********/ /************************************/ // Error attaches an error to the current context. The error is pushed to a list of errors. // It's a good idea to call Error for each error that occurred during the resolution of a request. // A middleware can be used to collect all the errors and push them to a database together, // print a log, or append it in the HTTP response. // Error will panic if err is nil. func (c *Context) Error(err error) *Error { if err == nil { panic("err is nil") } var parsedError *Error ok := errors.As(err, &parsedError) if !ok { parsedError = &Error{ Err: err, Type: ErrorTypePrivate, } } c.Errors = append(c.Errors, parsedError) return parsedError } /************************************/ /******** METADATA MANAGEMENT********/ /************************************/ // Set is used to store a new key/value pair exclusively for this context. // It also lazy initializes c.Keys if it was not used previously. func (c *Context) Set(key any, value any) { c.mu.Lock() defer c.mu.Unlock() if c.Keys == nil { c.Keys = make(map[any]any) } c.Keys[key] = value } // Get returns the value for the given key, ie: (value, true). // If the value does not exist it returns (nil, false) func (c *Context) Get(key any) (value any, exists bool) { c.mu.RLock() defer c.mu.RUnlock() value, exists = c.Keys[key] return } // MustGet returns the value for the given key if it exists, otherwise it panics. func (c *Context) MustGet(key any) any { if value, exists := c.Get(key); exists { return value } panic(fmt.Sprintf("key %v does not exist", key)) } func getTyped[T any](c *Context, key any) (res T) { if val, ok := c.Get(key); ok && val != nil { res, _ = val.(T) } return } // GetString returns the value associated with the key as a string. func (c *Context) GetString(key any) string { return getTyped[string](c, key) } // GetBool returns the value associated with the key as a boolean. func (c *Context) GetBool(key any) bool { return getTyped[bool](c, key) } // GetInt returns the value associated with the key as an integer. func (c *Context) GetInt(key any) int { return getTyped[int](c, key) } // GetInt8 returns the value associated with the key as an integer 8. func (c *Context) GetInt8(key any) int8 { return getTyped[int8](c, key) } // GetInt16 returns the value associated with the key as an integer 16. func (c *Context) GetInt16(key any) int16 { return getTyped[int16](c, key) } // GetInt32 returns the value associated with the key as an integer 32. func (c *Context) GetInt32(key any) int32 { return getTyped[int32](c, key) } // GetInt64 returns the value associated with the key as an integer 64. func (c *Context) GetInt64(key any) int64 { return getTyped[int64](c, key) } // GetUint returns the value associated with the key as an unsigned integer. func (c *Context) GetUint(key any) uint { return getTyped[uint](c, key) } // GetUint8 returns the value associated with the key as an unsigned integer 8. func (c *Context) GetUint8(key any) uint8 { return getTyped[uint8](c, key) } // GetUint16 returns the value associated with the key as an unsigned integer 16. func (c *Context) GetUint16(key any) uint16 { return getTyped[uint16](c, key) } // GetUint32 returns the value associated with the key as an unsigned integer 32. func (c *Context) GetUint32(key any) uint32 { return getTyped[uint32](c, key) } // GetUint64 returns the value associated with the key as an unsigned integer 64. func (c *Context) GetUint64(key any) uint64 { return getTyped[uint64](c, key) } // GetFloat32 returns the value associated with the key as a float32. func (c *Context) GetFloat32(key any) float32 { return getTyped[float32](c, key) } // GetFloat64 returns the value associated with the key as a float64. func (c *Context) GetFloat64(key any) float64 { return getTyped[float64](c, key) } // GetTime returns the value associated with the key as time. func (c *Context) GetTime(key any) time.Time { return getTyped[time.Time](c, key) } // GetDuration returns the value associated with the key as a duration. func (c *Context) GetDuration(key any) time.Duration { return getTyped[time.Duration](c, key) } // GetIntSlice returns the value associated with the key as a slice of integers. func (c *Context) GetIntSlice(key any) []int { return getTyped[[]int](c, key) } // GetInt8Slice returns the value associated with the key as a slice of int8 integers. func (c *Context) GetInt8Slice(key any) []int8 { return getTyped[[]int8](c, key) } // GetInt16Slice returns the value associated with the key as a slice of int16 integers. func (c *Context) GetInt16Slice(key any) []int16 { return getTyped[[]int16](c, key) } // GetInt32Slice returns the value associated with the key as a slice of int32 integers. func (c *Context) GetInt32Slice(key any) []int32 { return getTyped[[]int32](c, key) } // GetInt64Slice returns the value associated with the key as a slice of int64 integers. func (c *Context) GetInt64Slice(key any) []int64 { return getTyped[[]int64](c, key) } // GetUintSlice returns the value associated with the key as a slice of unsigned integers. func (c *Context) GetUintSlice(key any) []uint { return getTyped[[]uint](c, key) } // GetUint8Slice returns the value associated with the key as a slice of uint8 integers. func (c *Context) GetUint8Slice(key any) []uint8 { return getTyped[[]uint8](c, key) } // GetUint16Slice returns the value associated with the key as a slice of uint16 integers. func (c *Context) GetUint16Slice(key any) []uint16 { return getTyped[[]uint16](c, key) } // GetUint32Slice returns the value associated with the key as a slice of uint32 integers. func (c *Context) GetUint32Slice(key any) []uint32 { return getTyped[[]uint32](c, key) } // GetUint64Slice returns the value associated with the key as a slice of uint64 integers. func (c *Context) GetUint64Slice(key any) []uint64 { return getTyped[[]uint64](c, key) } // GetFloat32Slice returns the value associated with the key as a slice of float32 numbers. func (c *Context) GetFloat32Slice(key any) []float32 { return getTyped[[]float32](c, key) } // GetFloat64Slice returns the value associated with the key as a slice of float64 numbers. func (c *Context) GetFloat64Slice(key any) []float64 { return getTyped[[]float64](c, key) } // GetStringSlice returns the value associated with the key as a slice of strings. func (c *Context) GetStringSlice(key any) []string { return getTyped[[]string](c, key) } // GetStringMap returns the value associated with the key as a map of interfaces. func (c *Context) GetStringMap(key any) map[string]any { return getTyped[map[string]any](c, key) } // GetStringMapString returns the value associated with the key as a map of strings. func (c *Context) GetStringMapString(key any) map[string]string { return getTyped[map[string]string](c, key) } // GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings. func (c *Context) GetStringMapStringSlice(key any) map[string][]string { return getTyped[map[string][]string](c, key) } // Delete deletes the key from the Context's Key map, if it exists. // This operation is safe to be used by concurrent go-routines func (c *Context) Delete(key any) { c.mu.Lock() defer c.mu.Unlock() if c.Keys != nil { delete(c.Keys, key) } } /************************************/ /************ INPUT DATA ************/ /************************************/ // Param returns the value of the URL param. // It is a shortcut for c.Params.ByName(key) // // router.GET("/user/:id", func(c *gin.Context) { // // a GET request to /user/john // id := c.Param("id") // id == "john" // // a GET request to /user/john/ // id := c.Param("id") // id == "/john/" // }) func (c *Context) Param(key string) string { return c.Params.ByName(key) } // AddParam adds param to context and // replaces path param key with given value for e2e testing purposes // Example Route: "/user/:id" // AddParam("id", 1) // Result: "/user/1" func (c *Context) AddParam(key, value string) { c.Params = append(c.Params, Param{Key: key, Value: value}) } // Query returns the keyed url query value if it exists, // otherwise it returns an empty string `("")`. // It is shortcut for `c.Request.URL.Query().Get(key)` // // GET /path?id=1234&name=Manu&value= // c.Query("id") == "1234" // c.Query("name") == "Manu" // c.Query("value") == "" // c.Query("wtf") == "" func (c *Context) Query(key string) (value string) { value, _ = c.GetQuery(key) return } // DefaultQuery returns the keyed url query value if it exists, // otherwise it returns the specified defaultValue string. // See: Query() and GetQuery() for further information. // // GET /?name=Manu&lastname= // c.DefaultQuery("name", "unknown") == "Manu" // c.DefaultQuery("id", "none") == "none" // c.DefaultQuery("lastname", "none") == "" func (c *Context) DefaultQuery(key, defaultValue string) string { if value, ok := c.GetQuery(key); ok { return value } return defaultValue } // GetQuery is like Query(), it returns the keyed url query value // if it exists `(value, true)` (even when the value is an empty string), // otherwise it returns `("", false)`. // It is shortcut for `c.Request.URL.Query().Get(key)` // // GET /?name=Manu&lastname= // ("Manu", true) == c.GetQuery("name") // ("", false) == c.GetQuery("id") // ("", true) == c.GetQuery("lastname") func (c *Context) GetQuery(key string) (string, bool) { if values, ok := c.GetQueryArray(key); ok { return values[0], ok } return "", false } // QueryArray returns a slice of strings for a given query key. // The length of the slice depends on the number of params with the given key. func (c *Context) QueryArray(key string) (values []string) { values, _ = c.GetQueryArray(key) return } func (c *Context) initQueryCache() { if c.queryCache == nil { if c.Request != nil && c.Request.URL != nil { c.queryCache = c.Request.URL.Query() } else { c.queryCache = url.Values{} } } } // GetQueryArray returns a slice of strings for a given query key, plus // a boolean value whether at least one value exists for the given key. func (c *Context) GetQueryArray(key string) (values []string, ok bool) { c.initQueryCache() values, ok = c.queryCache[key] return } // QueryMap returns a map for a given query key. func (c *Context) QueryMap(key string) (dicts map[string]string) { dicts, _ = c.GetQueryMap(key) return } // GetQueryMap returns a map for a given query key, plus a boolean value // whether at least one value exists for the given key. func (c *Context) GetQueryMap(key string) (map[string]string, bool) { c.initQueryCache() return getMapFromFormData(c.queryCache, key) } // PostForm returns the specified key from a POST urlencoded form or multipart form // when it exists, otherwise it returns an empty string `("")`. func (c *Context) PostForm(key string) (value string) { value, _ = c.GetPostForm(key) return } // DefaultPostForm returns the specified key from a POST urlencoded form or multipart form // when it exists, otherwise it returns the specified defaultValue string. // See: PostForm() and GetPostForm() for further information. func (c *Context) DefaultPostForm(key, defaultValue string) string { if value, ok := c.GetPostForm(key); ok { return value } return defaultValue } // GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded // form or multipart form when it exists `(value, true)` (even when the value is an empty string), // otherwise it returns ("", false). // For example, during a PATCH request to update the user's email: // // email=mail@example.com --> ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com" // email= --> ("", true) := GetPostForm("email") // set email to "" // --> ("", false) := GetPostForm("email") // do nothing with email func (c *Context) GetPostForm(key string) (string, bool) { if values, ok := c.GetPostFormArray(key); ok { return values[0], ok } return "", false } // PostFormArray returns a slice of strings for a given form key. // The length of the slice depends on the number of params with the given key. func (c *Context) PostFormArray(key string) (values []string) { values, _ = c.GetPostFormArray(key) return } func (c *Context) initFormCache() { if c.formCache == nil { c.formCache = make(url.Values) req := c.Request if err := req.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil { if !errors.Is(err, http.ErrNotMultipart) { debugPrint("error on parse multipart form array: %v", err) } } c.formCache = req.PostForm } } // GetPostFormArray returns a slice of strings for a given form key, plus // a boolean value whether at least one value exists for the given key. func (c *Context) GetPostFormArray(key string) (values []string, ok bool) { c.initFormCache() values, ok = c.formCache[key] return } // PostFormMap returns a map for a given form key. func (c *Context) PostFormMap(key string) (dicts map[string]string) { dicts, _ = c.GetPostFormMap(key) return } // GetPostFormMap returns a map for a given form key, plus a boolean value // whether at least one value exists for the given key. func (c *Context) GetPostFormMap(key string) (map[string]string, bool) { c.initFormCache() return getMapFromFormData(c.formCache, key) } // getMapFromFormData return a map which satisfies conditions. // It parses from data with bracket notation like "key[subkey]=value" into a map. func getMapFromFormData(m map[string][]string, key string) (map[string]string, bool) { d := make(map[string]string) found := false keyLen := len(key) for k, v := range m { if len(k) < keyLen+3 { // key + "[" + at least one char + "]" continue } if k[:keyLen] != key || k[keyLen] != '[' { continue } if j := strings.IndexByte(k[keyLen+1:], ']'); j > 0 { found = true d[k[keyLen+1:keyLen+1+j]] = v[0] } } return d, found } // FormFile returns the first file for the provided form key. func (c *Context) FormFile(name string) (*multipart.FileHeader, error) { if c.Request.MultipartForm == nil { if err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil { return nil, err } } f, fh, err := c.Request.FormFile(name) if err != nil { return nil, err } f.Close() return fh, err } // MultipartForm is the parsed multipart form, including file uploads. func (c *Context) MultipartForm() (*multipart.Form, error) { err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory) return c.Request.MultipartForm, err } // SaveUploadedFile uploads the form file to specific dst. func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string, perm ...fs.FileMode) error { src, err := file.Open() if err != nil { return err } defer src.Close() var mode os.FileMode = 0o750 if len(perm) > 0 { mode = perm[0] } dir := filepath.Dir(dst) if err = os.MkdirAll(dir, mode); err != nil { return err } if err = os.Chmod(dir, mode); err != nil { return err } out, err := os.Create(dst) if err != nil { return err } defer out.Close() _, err = io.Copy(out, src) return err } // Bind checks the Method and Content-Type to select a binding engine automatically, // Depending on the "Content-Type" header different bindings are used, for example: // // "application/json" --> JSON binding // "application/xml" --> XML binding // // It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. // It decodes the json payload into the struct specified as a pointer. // It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid. func (c *Context) Bind(obj any) error { b := binding.Default(c.Request.Method, c.ContentType()) return c.MustBindWith(obj, b) } // BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON). func (c *Context) BindJSON(obj any) error { return c.MustBindWith(obj, binding.JSON) } // BindXML is a shortcut for c.MustBindWith(obj, binding.BindXML). func (c *Context) BindXML(obj any) error { return c.MustBindWith(obj, binding.XML) } // BindQuery is a shortcut for c.MustBindWith(obj, binding.Query). func (c *Context) BindQuery(obj any) error { return c.MustBindWith(obj, binding.Query) } // BindYAML is a shortcut for c.MustBindWith(obj, binding.YAML). func (c *Context) BindYAML(obj any) error { return c.MustBindWith(obj, binding.YAML) } // BindTOML is a shortcut for c.MustBindWith(obj, binding.TOML). func (c *Context) BindTOML(obj any) error { return c.MustBindWith(obj, binding.TOML) } // BindPlain is a shortcut for c.MustBindWith(obj, binding.Plain). func (c *Context) BindPlain(obj any) error { return c.MustBindWith(obj, binding.Plain) } // BindHeader is a shortcut for c.MustBindWith(obj, binding.Header). func (c *Context) BindHeader(obj any) error { return c.MustBindWith(obj, binding.Header) } // BindUri binds the passed struct pointer using binding.Uri. // It will abort the request with HTTP 400 if any error occurs. func (c *Context) BindUri(obj any) error { if err := c.ShouldBindUri(obj); err != nil { c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) //nolint: errcheck return err } return nil } // MustBindWith binds the passed struct pointer using the specified binding engine. // It will abort the request with HTTP 400 if any error occurs. // See the binding package. func (c *Context) MustBindWith(obj any, b binding.Binding) error { err := c.ShouldBindWith(obj, b) if err != nil { var maxBytesErr *http.MaxBytesError // Note: When using sonic or go-json as JSON encoder, they do not propagate the http.MaxBytesError error // https://github.com/goccy/go-json/issues/485 // https://github.com/bytedance/sonic/issues/800 switch { case errors.As(err, &maxBytesErr): c.AbortWithError(http.StatusRequestEntityTooLarge, err).SetType(ErrorTypeBind) //nolint: errcheck default: c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) //nolint: errcheck } return err } return nil } // ShouldBind checks the Method and Content-Type to select a binding engine automatically, // Depending on the "Content-Type" header different bindings are used, for example: // // "application/json" --> JSON binding // "application/xml" --> XML binding // // It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. // It decodes the json payload into the struct specified as a pointer. // Like c.Bind() but this method does not set the response status code to 400 or abort if input is not valid. func (c *Context) ShouldBind(obj any) error { b := binding.Default(c.Request.Method, c.ContentType()) return c.ShouldBindWith(obj, b) } // ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON). // // Example: // // POST /user // Content-Type: application/json // // Request Body: // { // "name": "Manu", // "age": 20 // } // // type User struct { // Name string `json:"name"` // Age int `json:"age"` // } // // var user User // if err := c.ShouldBindJSON(&user); err != nil { // c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) // return // } // c.JSON(http.StatusOK, user) func (c *Context) ShouldBindJSON(obj any) error { return c.ShouldBindWith(obj, binding.JSON) } // ShouldBindXML is a shortcut for c.ShouldBindWith(obj, binding.XML). // It works like ShouldBindJSON but binds the request body as XML data. func (c *Context) ShouldBindXML(obj any) error { return c.ShouldBindWith(obj, binding.XML) } // ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, binding.Query). // It works like ShouldBindJSON but binds query parameters from the URL. func (c *Context) ShouldBindQuery(obj any) error { return c.ShouldBindWith(obj, binding.Query) } // ShouldBindYAML is a shortcut for c.ShouldBindWith(obj, binding.YAML). // It works like ShouldBindJSON but binds the request body as YAML data. func (c *Context) ShouldBindYAML(obj any) error { return c.ShouldBindWith(obj, binding.YAML) } // ShouldBindTOML is a shortcut for c.ShouldBindWith(obj, binding.TOML). // It works like ShouldBindJSON but binds the request body as TOML data. func (c *Context) ShouldBindTOML(obj any) error { return c.ShouldBindWith(obj, binding.TOML) } // ShouldBindPlain is a shortcut for c.ShouldBindWith(obj, binding.Plain). // It works like ShouldBindJSON but binds plain text data from the request body. func (c *Context) ShouldBindPlain(obj any) error { return c.ShouldBindWith(obj, binding.Plain) } // ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, binding.Header). // It works like ShouldBindJSON but binds values from HTTP headers. func (c *Context) ShouldBindHeader(obj any) error { return c.ShouldBindWith(obj, binding.Header) } // ShouldBindUri binds the passed struct pointer using the specified binding engine. // It works like ShouldBindJSON but binds parameters from the URI. func (c *Context) ShouldBindUri(obj any) error { m := make(map[string][]string, len(c.Params)) for _, v := range c.Params { m[v.Key] = []string{v.Value} } return binding.Uri.BindUri(m, obj) } // ShouldBindWith binds the passed struct pointer using the specified binding engine. // See the binding package. func (c *Context) ShouldBindWith(obj any, b binding.Binding) error { return b.Bind(c.Request, obj) } // ShouldBindBodyWith is similar with ShouldBindWith, but it stores the request // body into the context, and reuse when it is called again. // // NOTE: This method reads the body before binding. So you should use // ShouldBindWith for better performance if you need to call only once. func (c *Context) ShouldBindBodyWith(obj any, bb binding.BindingBody) (err error) { var body []byte if cb, ok := c.Get(BodyBytesKey); ok { if cbb, ok := cb.([]byte); ok { body = cbb } } if body == nil { body, err = io.ReadAll(c.Request.Body) if err != nil { return err } c.Set(BodyBytesKey, body) } return bb.BindBody(body, obj) } // ShouldBindBodyWithJSON is a shortcut for c.ShouldBindBodyWith(obj, binding.JSON). func (c *Context) ShouldBindBodyWithJSON(obj any) error { return c.ShouldBindBodyWith(obj, binding.JSON) } // ShouldBindBodyWithXML is a shortcut for c.ShouldBindBodyWith(obj, binding.XML). func (c *Context) ShouldBindBodyWithXML(obj any) error { return c.ShouldBindBodyWith(obj, binding.XML) } // ShouldBindBodyWithYAML is a shortcut for c.ShouldBindBodyWith(obj, binding.YAML). func (c *Context) ShouldBindBodyWithYAML(obj any) error { return c.ShouldBindBodyWith(obj, binding.YAML) } // ShouldBindBodyWithTOML is a shortcut for c.ShouldBindBodyWith(obj, binding.TOML). func (c *Context) ShouldBindBodyWithTOML(obj any) error { return c.ShouldBindBodyWith(obj, binding.TOML) } // ShouldBindBodyWithPlain is a shortcut for c.ShouldBindBodyWith(obj, binding.Plain). func (c *Context) ShouldBindBodyWithPlain(obj any) error { return c.ShouldBindBodyWith(obj, binding.Plain) } // ClientIP implements one best effort algorithm to return the real client IP. // It calls c.RemoteIP() under the hood, to check if the remote IP is a trusted proxy or not. // If it is it will then try to parse the headers defined in Engine.RemoteIPHeaders (defaulting to [X-Forwarded-For, X-Real-IP]). // If the headers are not syntactically valid OR the remote IP does not correspond to a trusted proxy, // the remote IP (coming from Request.RemoteAddr) is returned. func (c *Context) ClientIP() string { // Check if we're running on a trusted platform, continue running backwards if error if c.engine.TrustedPlatform != "" { // Developers can define their own header of Trusted Platform or use predefined constants if addr := c.requestHeader(c.engine.TrustedPlatform); addr != "" { return addr } } // Legacy "AppEngine" flag if c.engine.AppEngine { log.Println(`The AppEngine flag is going to be deprecated. Please check issues #2723 and #2739 and use 'TrustedPlatform: gin.PlatformGoogleAppEngine' instead.`) if addr := c.requestHeader("X-Appengine-Remote-Addr"); addr != "" { return addr } } // It also checks if the remoteIP is a trusted proxy or not. // In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks // defined by Engine.SetTrustedProxies() remoteIP := net.ParseIP(c.RemoteIP()) if remoteIP == nil { return "" } trusted := c.engine.isTrustedProxy(remoteIP) if trusted && c.engine.ForwardedByClientIP && c.engine.RemoteIPHeaders != nil { for _, headerName := range c.engine.RemoteIPHeaders { headerValue := strings.Join(c.Request.Header.Values(headerName), ",") ip, valid := c.engine.validateHeader(headerValue) if valid { return ip } } } return remoteIP.String() } // RemoteIP parses the IP from Request.RemoteAddr, normalizes and returns the IP (without the port). func (c *Context) RemoteIP() string { ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)) if err != nil { return "" } return ip } // ContentType returns the Content-Type header of the request. func (c *Context) ContentType() string { return filterFlags(c.requestHeader("Content-Type")) } // IsWebsocket returns true if the request headers indicate that a websocket // handshake is being initiated by the client. func (c *Context) IsWebsocket() bool { if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") && strings.EqualFold(c.requestHeader("Upgrade"), "websocket") { return true } return false } func (c *Context) requestHeader(key string) string { return c.Request.Header.Get(key) } /************************************/ /******** RESPONSE RENDERING ********/
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
true
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/version.go
version.go
// Copyright 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 gin // Version is the current gin framework's version. const Version = "v1.11.0"
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/response_writer.go
response_writer.go
// 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 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 interface { http.ResponseWriter http.Hijacker http.Flusher http.CloseNotifier // Status returns the HTTP response status code of the current request. Status() int // Size returns the number 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 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 size int status int } var _ ResponseWriter = (*responseWriter)(nil) func (w *responseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } func (w *responseWriter) reset(writer http.ResponseWriter) { w.ResponseWriter = writer w.size = noWritten w.status = defaultStatus } func (w *responseWriter) WriteHeader(code int) { if code > 0 && w.status != code { if w.Written() { debugPrint("[WARNING] Headers were already written. Wanted to override status code %d with %d", w.status, code) return } w.status = code } } func (w *responseWriter) WriteHeaderNow() { if !w.Written() { w.size = 0 w.ResponseWriter.WriteHeader(w.status) } } func (w *responseWriter) Write(data []byte) (n int, err error) { w.WriteHeaderNow() n, err = w.ResponseWriter.Write(data) w.size += n return } func (w *responseWriter) WriteString(s string) (n int, err error) { w.WriteHeaderNow() n, err = io.WriteString(w.ResponseWriter, s) w.size += n return } func (w *responseWriter) Status() int { return w.status } func (w *responseWriter) Size() int { return w.size } func (w *responseWriter) Written() bool { return w.size != noWritten } // Hijack implements the http.Hijacker interface. func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { // Allow hijacking before any data is written (size == -1) or after headers are written (size == 0), // but not after body data is written (size > 0). For compatibility with websocket libraries (e.g., github.com/coder/websocket) if w.size > 0 { return nil, nil, errHijackAlreadyWritten } if w.size < 0 { w.size = 0 } return w.ResponseWriter.(http.Hijacker).Hijack() } // CloseNotify implements the http.CloseNotifier interface. func (w *responseWriter) CloseNotify() <-chan bool { return w.ResponseWriter.(http.CloseNotifier).CloseNotify() } // Flush implements the http.Flusher interface. func (w *responseWriter) Flush() { w.WriteHeaderNow() if f, ok := w.ResponseWriter.(http.Flusher); ok { f.Flush() } } func (w *responseWriter) Pusher() (pusher http.Pusher) { if pusher, ok := w.ResponseWriter.(http.Pusher); ok { return pusher } return nil }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/doc.go
doc.go
/* Package gin implements a HTTP web framework called gin. See https://gin-gonic.com/ for more information about gin. Example: package main import "github.com/gin-gonic/gin" func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.Run() // listen and serve on 0.0.0.0:8080 } */ package gin // import "github.com/gin-gonic/gin"
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/logger.go
logger.go
// 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 gin import ( "fmt" "io" "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;45m" cyan = "\033[97;46m" reset = "\033[0m" ) var consoleColorMode = autoColor // LoggerConfig defines the config for Logger middleware. type LoggerConfig struct { // Optional. Default 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 written. // Optional. SkipPaths []string // Skip is a Skipper that indicates which logs should not be written. // Optional. Skip Skipper } // Skipper is a function to skip logs based on provided Context type Skipper func(c *Context) bool // LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter type LogFormatter func(params LogFormatterParams) string // LogFormatterParams is the structure any formatter will be handed when time to log comes type LogFormatterParams struct { Request *http.Request // TimeStamp shows the time after the server returns a response. TimeStamp time.Time // StatusCode is HTTP response code. StatusCode int // Latency is how much time the server cost to process a certain request. Latency time.Duration // ClientIP equals Context's ClientIP method. ClientIP string // Method is the HTTP method given to the request. Method string // Path is a path the client requests. Path string // ErrorMessage is set if error has occurred in processing the request. ErrorMessage string // isTerm shows whether gin's output descriptor refers to a terminal. isTerm bool // BodySize is the size of the Response Body BodySize int // Keys are the keys set on the request's context. Keys map[any]any } // StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal. func (p *LogFormatterParams) StatusCodeColor() string { code := p.StatusCode switch { case code >= http.StatusContinue && code < http.StatusOK: return white case code >= http.StatusOK && code < http.StatusMultipleChoices: return green case code >= http.StatusMultipleChoices && code < http.StatusBadRequest: return white case code >= http.StatusBadRequest && code < http.StatusInternalServerError: return yellow default: return red } } // LatencyColor is the ANSI color for latency func (p *LogFormatterParams) LatencyColor() string { latency := p.Latency switch { case latency < time.Millisecond*100: return white case latency < time.Millisecond*200: return green case latency < time.Millisecond*300: return cyan case latency < time.Millisecond*500: return blue case latency < time.Second: return yellow case latency < time.Second*2: return magenta default: return red } } // MethodColor is the ANSI color for appropriately logging http method to a terminal. func (p *LogFormatterParams) MethodColor() string { method := p.Method switch method { case http.MethodGet: return blue case http.MethodPost: return cyan case http.MethodPut: return yellow case http.MethodDelete: return red case http.MethodPatch: return green case http.MethodHead: return magenta case http.MethodOptions: return white default: return reset } } // ResetColor resets all escape attributes. func (p *LogFormatterParams) ResetColor() string { return reset } // IsOutputColor indicates whether can colors be outputted to the log. func (p *LogFormatterParams) IsOutputColor() bool { return consoleColorMode == forceColor || (consoleColorMode == autoColor && p.isTerm) } // defaultLogFormatter is the default log format function Logger middleware uses. var defaultLogFormatter = func(param LogFormatterParams) string { var statusColor, methodColor, resetColor, latencyColor string if param.IsOutputColor() { statusColor = param.StatusCodeColor() methodColor = param.MethodColor() resetColor = param.ResetColor() latencyColor = param.LatencyColor() } switch { case param.Latency > time.Minute: param.Latency = param.Latency.Truncate(time.Second * 10) case param.Latency > time.Second: param.Latency = param.Latency.Truncate(time.Millisecond * 10) case param.Latency > time.Millisecond: param.Latency = param.Latency.Truncate(time.Microsecond * 10) } return fmt.Sprintf("[GIN] %v |%s %3d %s|%s %8v %s| %15s |%s %-7s %s %#v\n%s", param.TimeStamp.Format("2006/01/02 - 15:04:05"), statusColor, param.StatusCode, resetColor, latencyColor, param.Latency, resetColor, param.ClientIP, methodColor, param.Method, resetColor, param.Path, param.ErrorMessage, ) } // DisableConsoleColor disables color output in the console. func DisableConsoleColor() { consoleColorMode = disableColor } // ForceConsoleColor force color output in the console. func ForceConsoleColor() { consoleColorMode = forceColor } // ErrorLogger returns a HandlerFunc for any error type. func ErrorLogger() HandlerFunc { return ErrorLoggerT(ErrorTypeAny) } // ErrorLoggerT returns a HandlerFunc for a given error type. func ErrorLoggerT(typ ErrorType) HandlerFunc { return func(c *Context) { c.Next() errors := c.Errors.ByType(typ) if len(errors) > 0 { c.JSON(-1, errors) } } } // Logger instances a Logger middleware that will write the logs to gin.DefaultWriter. // By default, gin.DefaultWriter = os.Stdout. func Logger() HandlerFunc { return LoggerWithConfig(LoggerConfig{}) } // LoggerWithFormatter instance a Logger middleware with the specified log format function. func LoggerWithFormatter(f LogFormatter) HandlerFunc { return LoggerWithConfig(LoggerConfig{ Formatter: f, }) } // LoggerWithWriter instance a Logger middleware with the specified writer buffer. // Example: os.Stdout, a file opened in write mode, a socket... func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc { return LoggerWithConfig(LoggerConfig{ Output: out, SkipPaths: notlogged, }) } // LoggerWithConfig instance a Logger middleware with config. func LoggerWithConfig(conf LoggerConfig) HandlerFunc { formatter := conf.Formatter if formatter == nil { formatter = defaultLogFormatter } out := conf.Output if out == nil { out = DefaultWriter } notlogged := conf.SkipPaths isTerm := true if w, ok := out.(*os.File); !ok || os.Getenv("TERM") == "dumb" || (!isatty.IsTerminal(w.Fd()) && !isatty.IsCygwinTerminal(w.Fd())) { isTerm = false } var skip map[string]struct{} if length := len(notlogged); length > 0 { skip = make(map[string]struct{}, length) for _, path := range notlogged { skip[path] = struct{}{} } } return func(c *Context) { // Start timer start := time.Now() path := c.Request.URL.Path raw := c.Request.URL.RawQuery // Process request c.Next() // Log only when it is not being skipped if _, ok := skip[path]; ok || (conf.Skip != nil && conf.Skip(c)) { return } param := LogFormatterParams{ Request: c.Request, isTerm: isTerm, Keys: c.Keys, } // Stop timer param.TimeStamp = time.Now() param.Latency = param.TimeStamp.Sub(start) param.ClientIP = c.ClientIP() param.Method = c.Request.Method param.StatusCode = c.Writer.Status() param.ErrorMessage = c.Errors.ByType(ErrorTypePrivate).String() param.BodySize = c.Writer.Size() if raw != "" { path = path + "?" + raw } param.Path = path fmt.Fprint(out, formatter(param)) } }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/fs.go
fs.go
// Copyright 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.FileSystem } // Open passes `Open` to the upstream implementation without `Readdir` functionality. func (o OnlyFilesFS) Open(name string) (http.File, error) { f, err := o.FileSystem.Open(name) 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 } // Readdir 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 http.FileServer(). // It is used internally in router.Static(). // if listDirectory == true, then it works the same as http.Dir(), // otherwise it returns a filesystem that prevents http.FileServer() to list the directory files. func Dir(root string, listDirectory bool) http.FileSystem { fs := http.Dir(root) if listDirectory { return fs } return &OnlyFilesFS{FileSystem: fs} }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/response_writer_test.go
response_writer_test.go
// 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 gin import ( "bufio" "net" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // TODO // func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { // 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.Flusher = ResponseWriter(&responseWriter{}) _ http.CloseNotifier = ResponseWriter(&responseWriter{}) ) func init() { SetMode(TestMode) } func TestResponseWriterUnwrap(t *testing.T) { testWriter := httptest.NewRecorder() writer := &responseWriter{ResponseWriter: testWriter} assert.Same(t, testWriter, writer.Unwrap()) } func TestResponseWriterReset(t *testing.T) { testWriter := httptest.NewRecorder() writer := &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.Equal(t, http.StatusOK, w.Status()) assert.False(t, w.Written()) } func TestResponseWriterWriteHeader(t *testing.T) { testWriter := httptest.NewRecorder() writer := &responseWriter{} writer.reset(testWriter) w := ResponseWriter(writer) w.WriteHeader(http.StatusMultipleChoices) assert.False(t, w.Written()) assert.Equal(t, http.StatusMultipleChoices, w.Status()) assert.NotEqual(t, http.StatusMultipleChoices, testWriter.Code) w.WriteHeader(-1) assert.Equal(t, http.StatusMultipleChoices, w.Status()) } func TestResponseWriterWriteHeadersNow(t *testing.T) { testWriter := httptest.NewRecorder() writer := &responseWriter{} writer.reset(testWriter) w := ResponseWriter(writer) w.WriteHeader(http.StatusMultipleChoices) w.WriteHeaderNow() assert.True(t, w.Written()) assert.Equal(t, 0, w.Size()) assert.Equal(t, http.StatusMultipleChoices, testWriter.Code) writer.size = 10 w.WriteHeaderNow() assert.Equal(t, 10, w.Size()) } func TestResponseWriterWrite(t *testing.T) { testWriter := httptest.NewRecorder() writer := &responseWriter{} writer.reset(testWriter) w := ResponseWriter(writer) n, err := w.Write([]byte("hola")) assert.Equal(t, 4, n) assert.Equal(t, 4, w.Size()) assert.Equal(t, http.StatusOK, w.Status()) assert.Equal(t, http.StatusOK, testWriter.Code) assert.Equal(t, "hola", testWriter.Body.String()) require.NoError(t, err) n, err = w.Write([]byte(" adios")) assert.Equal(t, 6, n) assert.Equal(t, 10, w.Size()) assert.Equal(t, "hola adios", testWriter.Body.String()) require.NoError(t, err) } func TestResponseWriterHijack(t *testing.T) { testWriter := httptest.NewRecorder() writer := &responseWriter{} writer.reset(testWriter) w := ResponseWriter(writer) assert.Panics(t, func() { _, _, err := w.Hijack() require.NoError(t, err) }) assert.True(t, w.Written()) assert.Panics(t, func() { w.CloseNotify() }) w.Flush() } type mockHijacker struct { *httptest.ResponseRecorder hijacked bool } // Hijack implements the http.Hijacker interface. It just records that it was called. func (m *mockHijacker) Hijack() (net.Conn, *bufio.ReadWriter, error) { m.hijacked = true return nil, nil, nil } func TestResponseWriterHijackAfterWrite(t *testing.T) { tests := []struct { name string action func(w ResponseWriter) error // Action to perform before hijacking expectWrittenBeforeHijack bool expectHijackSuccess bool expectWrittenAfterHijack bool expectError error }{ { name: "hijack before write should succeed", action: func(w ResponseWriter) error { return nil }, expectWrittenBeforeHijack: false, expectHijackSuccess: true, expectWrittenAfterHijack: true, // Hijack itself marks the writer as written expectError: nil, }, { name: "hijack after write should fail", action: func(w ResponseWriter) error { _, err := w.Write([]byte("test")) return err }, expectWrittenBeforeHijack: true, expectHijackSuccess: false, expectWrittenAfterHijack: true, expectError: errHijackAlreadyWritten, }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { hijacker := &mockHijacker{ResponseRecorder: httptest.NewRecorder()} writer := &responseWriter{} writer.reset(hijacker) w := ResponseWriter(writer) // Check initial state assert.False(t, w.Written(), "should not be written initially") // Perform pre-hijack action require.NoError(t, tc.action(w), "unexpected error during pre-hijack action") // Check state before hijacking assert.Equal(t, tc.expectWrittenBeforeHijack, w.Written(), "unexpected w.Written() state before hijack") // Attempt to hijack _, _, hijackErr := w.Hijack() // Check results require.ErrorIs(t, hijackErr, tc.expectError, "unexpected error from Hijack()") assert.Equal(t, tc.expectHijackSuccess, hijacker.hijacked, "unexpected hijacker.hijacked state") assert.Equal(t, tc.expectWrittenAfterHijack, w.Written(), "unexpected w.Written() state after hijack") }) } } // Test: WebSocket compatibility - allow hijack after WriteHeaderNow(), but block after body data. func TestResponseWriterHijackAfterWriteHeaderNow(t *testing.T) { tests := []struct { name string action func(w ResponseWriter) error expectWrittenBeforeHijack bool expectHijackSuccess bool expectWrittenAfterHijack bool expectError error }{ { name: "hijack after WriteHeaderNow only should succeed (websocket pattern)", action: func(w ResponseWriter) error { w.WriteHeaderNow() // Simulate websocket.Accept() behavior return nil }, expectWrittenBeforeHijack: true, expectHijackSuccess: true, // NEW BEHAVIOR: allow hijack after just header write expectWrittenAfterHijack: true, expectError: nil, }, { name: "hijack after WriteHeaderNow + Write should fail", action: func(w ResponseWriter) error { w.WriteHeaderNow() _, err := w.Write([]byte("test")) return err }, expectWrittenBeforeHijack: true, expectHijackSuccess: false, expectWrittenAfterHijack: true, expectError: errHijackAlreadyWritten, }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { hijacker := &mockHijacker{ResponseRecorder: httptest.NewRecorder()} writer := &responseWriter{} writer.reset(hijacker) w := ResponseWriter(writer) require.NoError(t, tc.action(w), "unexpected error during pre-hijack action") assert.Equal(t, tc.expectWrittenBeforeHijack, w.Written(), "unexpected w.Written() state before hijack") _, _, hijackErr := w.Hijack() if tc.expectError == nil { require.NoError(t, hijackErr, "expected hijack to succeed") } else { require.ErrorIs(t, hijackErr, tc.expectError, "unexpected error from Hijack()") } assert.Equal(t, tc.expectHijackSuccess, hijacker.hijacked, "unexpected hijacker.hijacked state") assert.Equal(t, tc.expectWrittenAfterHijack, w.Written(), "unexpected w.Written() state after hijack") }) } } func TestResponseWriterFlush(t *testing.T) { testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { writer := &responseWriter{} writer.reset(w) writer.WriteHeader(http.StatusInternalServerError) writer.Flush() })) defer testServer.Close() // should return 500 resp, err := http.Get(testServer.URL) require.NoError(t, err) assert.Equal(t, http.StatusInternalServerError, resp.StatusCode) } func TestResponseWriterStatusCode(t *testing.T) { testWriter := httptest.NewRecorder() writer := &responseWriter{} writer.reset(testWriter) w := ResponseWriter(writer) w.WriteHeader(http.StatusOK) w.WriteHeaderNow() assert.Equal(t, http.StatusOK, w.Status()) assert.True(t, w.Written()) w.WriteHeader(http.StatusUnauthorized) // status must be 200 although we tried to change it assert.Equal(t, http.StatusOK, w.Status()) } // mockPusherResponseWriter is an http.ResponseWriter that implements http.Pusher. type mockPusherResponseWriter struct { http.ResponseWriter } func (m *mockPusherResponseWriter) Push(target string, opts *http.PushOptions) error { return nil } // nonPusherResponseWriter is an http.ResponseWriter that does not implement http.Pusher. type nonPusherResponseWriter struct { http.ResponseWriter } func TestPusherWithPusher(t *testing.T) { rw := &mockPusherResponseWriter{} w := &responseWriter{ResponseWriter: rw} pusher := w.Pusher() assert.NotNil(t, pusher, "Expected pusher to be non-nil") } func TestPusherWithoutPusher(t *testing.T) { rw := &nonPusherResponseWriter{} w := &responseWriter{ResponseWriter: rw} pusher := w.Pusher() assert.Nil(t, pusher, "Expected pusher to be nil") }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/tree_test.go
tree_test.go
// Copyright 2013 Julien Schmidt. All rights reserved. // 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 ( "fmt" "reflect" "regexp" "strings" "testing" ) // Used as a workaround since we can't compare functions or their addresses var fakeHandlerValue string func fakeHandler(val string) HandlersChain { return HandlersChain{func(c *Context) { fakeHandlerValue = val }} } type testRequests []struct { path string nilHandler bool route string ps Params } func getParams() *Params { ps := make(Params, 0, 20) return &ps } func getSkippedNodes() *[]skippedNode { ps := make([]skippedNode, 0, 20) return &ps } func checkRequests(t *testing.T, tree *node, requests testRequests, unescapes ...bool) { unescape := false if len(unescapes) >= 1 { unescape = unescapes[0] } for _, request := range requests { value := tree.getValue(request.path, getParams(), getSkippedNodes(), unescape) if value.handlers == nil { if !request.nilHandler { t.Errorf("handle mismatch for route '%s': Expected non-nil handle", request.path) } } else if request.nilHandler { t.Errorf("handle mismatch for route '%s': Expected nil handle", request.path) } else { value.handlers[0](nil) if fakeHandlerValue != request.route { t.Errorf("handle mismatch for route '%s': Wrong handle (%s != %s)", request.path, fakeHandlerValue, request.route) } } if value.params != nil { if !reflect.DeepEqual(*value.params, request.ps) { t.Errorf("Params mismatch for route '%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", n.path, n.priority, prio, ) } return prio } func TestCountParams(t *testing.T) { if countParams("/path/:param1/static/*catch-all") != 2 { t.Fail() } if countParams(strings.Repeat("/: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.html", "/Ξ±", "/Ξ²", } 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", nil}, {"/co", false, "/co", nil}, {"/con", true, "", nil}, // key mismatch {"/cona", true, "", nil}, // key mismatch {"/no", true, "", nil}, // no matching child {"/ab", false, "/ab", nil}, {"/Ξ±", false, "/Ξ±", nil}, {"/Ξ²", false, "/Ξ²", nil}, }) checkPriorities(t, tree) } func TestTreeWildcard(t *testing.T) { tree := &node{} routes := [...]string{ "/", "/cmd/:tool/", "/cmd/:tool/:sub", "/cmd/whoami", "/cmd/whoami/root", "/cmd/whoami/root/", "/src/*filepath", "/search/", "/search/:query", "/search/gin-gonic", "/search/google", "/user_:name", "/user_:name/about", "/files/:dir/*filepath", "/doc/", "/doc/go_faq.html", "/doc/go1.html", "/info/:user/public", "/info/:user/project/:project", "/info/:user/project/golang", "/aa/*xx", "/ab/*xx", "/:cc", "/c1/:dd/e", "/c1/:dd/e1", "/:cc/cc", "/:cc/:dd/ee", "/:cc/:dd/:ee/ff", "/:cc/:dd/:ee/:ff/gg", "/:cc/:dd/:ee/:ff/:gg/hh", "/get/test/abc/", "/get/:param/abc/", "/something/:paramname/thirdthing", "/something/secondthing/test", "/get/abc", "/get/:param", "/get/abc/123abc", "/get/abc/:param", "/get/abc/123abc/xxx8", "/get/abc/123abc/:param", "/get/abc/123abc/xxx8/1234", "/get/abc/123abc/xxx8/:param", "/get/abc/123abc/xxx8/1234/ffas", "/get/abc/123abc/xxx8/1234/:param", "/get/abc/123abc/xxx8/1234/kkdd/12c", "/get/abc/123abc/xxx8/1234/kkdd/:param", "/get/abc/:param/test", "/get/abc/123abd/:param", "/get/abc/123abddd/:param", "/get/abc/123/:param", "/get/abc/123abg/:param", "/get/abc/123abf/:param", "/get/abc/123abfff/:param", "/get/abc/escaped_colon/test\\:param", } for _, route := range routes { tree.addRoute(route, fakeHandler(route)) } checkRequests(t, tree, testRequests{ {"/", false, "/", nil}, {"/cmd/test", true, "/cmd/:tool/", Params{Param{"tool", "test"}}}, {"/cmd/test/", false, "/cmd/:tool/", Params{Param{"tool", "test"}}}, {"/cmd/test/3", false, "/cmd/:tool/:sub", Params{Param{Key: "tool", Value: "test"}, Param{Key: "sub", Value: "3"}}}, {"/cmd/who", true, "/cmd/:tool/", Params{Param{"tool", "who"}}}, {"/cmd/who/", false, "/cmd/:tool/", Params{Param{"tool", "who"}}}, {"/cmd/whoami", false, "/cmd/whoami", nil}, {"/cmd/whoami/", true, "/cmd/whoami", nil}, {"/cmd/whoami/r", false, "/cmd/:tool/:sub", Params{Param{Key: "tool", Value: "whoami"}, Param{Key: "sub", Value: "r"}}}, {"/cmd/whoami/r/", true, "/cmd/:tool/:sub", Params{Param{Key: "tool", Value: "whoami"}, Param{Key: "sub", Value: "r"}}}, {"/cmd/whoami/root", false, "/cmd/whoami/root", nil}, {"/cmd/whoami/root/", false, "/cmd/whoami/root/", nil}, {"/src/", false, "/src/*filepath", Params{Param{Key: "filepath", Value: "/"}}}, {"/src/some/file.png", false, "/src/*filepath", Params{Param{Key: "filepath", Value: "/some/file.png"}}}, {"/search/", false, "/search/", nil}, {"/search/someth!ng+in+ΓΌnΓ¬codΓ©", false, "/search/:query", Params{Param{Key: "query", Value: "someth!ng+in+ΓΌnΓ¬codΓ©"}}}, {"/search/someth!ng+in+ΓΌnΓ¬codΓ©/", true, "", Params{Param{Key: "query", Value: "someth!ng+in+ΓΌnΓ¬codΓ©"}}}, {"/search/gin", false, "/search/:query", Params{Param{"query", "gin"}}}, {"/search/gin-gonic", false, "/search/gin-gonic", nil}, {"/search/google", false, "/search/google", nil}, {"/user_gopher", false, "/user_:name", Params{Param{Key: "name", Value: "gopher"}}}, {"/user_gopher/about", false, "/user_:name/about", Params{Param{Key: "name", Value: "gopher"}}}, {"/files/js/inc/framework.js", false, "/files/:dir/*filepath", Params{Param{Key: "dir", Value: "js"}, Param{Key: "filepath", Value: "/inc/framework.js"}}}, {"/info/gordon/public", false, "/info/:user/public", Params{Param{Key: "user", Value: "gordon"}}}, {"/info/gordon/project/go", false, "/info/:user/project/:project", Params{Param{Key: "user", Value: "gordon"}, Param{Key: "project", Value: "go"}}}, {"/info/gordon/project/golang", false, "/info/:user/project/golang", Params{Param{Key: "user", Value: "gordon"}}}, {"/aa/aa", false, "/aa/*xx", Params{Param{Key: "xx", Value: "/aa"}}}, {"/ab/ab", false, "/ab/*xx", Params{Param{Key: "xx", Value: "/ab"}}}, {"/a", false, "/:cc", Params{Param{Key: "cc", Value: "a"}}}, // * Error with argument being intercepted // new PR handle (/all /all/cc /a/cc) // fix PR: https://github.com/gin-gonic/gin/pull/2796 {"/all", false, "/:cc", Params{Param{Key: "cc", Value: "all"}}}, {"/d", false, "/:cc", Params{Param{Key: "cc", Value: "d"}}}, {"/ad", false, "/:cc", Params{Param{Key: "cc", Value: "ad"}}}, {"/dd", false, "/:cc", Params{Param{Key: "cc", Value: "dd"}}}, {"/dddaa", false, "/:cc", Params{Param{Key: "cc", Value: "dddaa"}}}, {"/aa", false, "/:cc", Params{Param{Key: "cc", Value: "aa"}}}, {"/aaa", false, "/:cc", Params{Param{Key: "cc", Value: "aaa"}}}, {"/aaa/cc", false, "/:cc/cc", Params{Param{Key: "cc", Value: "aaa"}}}, {"/ab", false, "/:cc", Params{Param{Key: "cc", Value: "ab"}}}, {"/abb", false, "/:cc", Params{Param{Key: "cc", Value: "abb"}}}, {"/abb/cc", false, "/:cc/cc", Params{Param{Key: "cc", Value: "abb"}}}, {"/allxxxx", false, "/:cc", Params{Param{Key: "cc", Value: "allxxxx"}}}, {"/alldd", false, "/:cc", Params{Param{Key: "cc", Value: "alldd"}}}, {"/all/cc", false, "/:cc/cc", Params{Param{Key: "cc", Value: "all"}}}, {"/a/cc", false, "/:cc/cc", Params{Param{Key: "cc", Value: "a"}}}, {"/c1/d/e", false, "/c1/:dd/e", Params{Param{Key: "dd", Value: "d"}}}, {"/c1/d/e1", false, "/c1/:dd/e1", Params{Param{Key: "dd", Value: "d"}}}, {"/c1/d/ee", false, "/:cc/:dd/ee", Params{Param{Key: "cc", Value: "c1"}, Param{Key: "dd", Value: "d"}}}, {"/cc/cc", false, "/:cc/cc", Params{Param{Key: "cc", Value: "cc"}}}, {"/ccc/cc", false, "/:cc/cc", Params{Param{Key: "cc", Value: "ccc"}}}, {"/deedwjfs/cc", false, "/:cc/cc", Params{Param{Key: "cc", Value: "deedwjfs"}}}, {"/acllcc/cc", false, "/:cc/cc", Params{Param{Key: "cc", Value: "acllcc"}}}, {"/get/test/abc/", false, "/get/test/abc/", nil}, {"/get/te/abc/", false, "/get/:param/abc/", Params{Param{Key: "param", Value: "te"}}}, {"/get/testaa/abc/", false, "/get/:param/abc/", Params{Param{Key: "param", Value: "testaa"}}}, {"/get/xx/abc/", false, "/get/:param/abc/", Params{Param{Key: "param", Value: "xx"}}}, {"/get/tt/abc/", false, "/get/:param/abc/", Params{Param{Key: "param", Value: "tt"}}}, {"/get/a/abc/", false, "/get/:param/abc/", Params{Param{Key: "param", Value: "a"}}}, {"/get/t/abc/", false, "/get/:param/abc/", Params{Param{Key: "param", Value: "t"}}}, {"/get/aa/abc/", false, "/get/:param/abc/", Params{Param{Key: "param", Value: "aa"}}}, {"/get/abas/abc/", false, "/get/:param/abc/", Params{Param{Key: "param", Value: "abas"}}}, {"/something/secondthing/test", false, "/something/secondthing/test", nil}, {"/something/abcdad/thirdthing", false, "/something/:paramname/thirdthing", Params{Param{Key: "paramname", Value: "abcdad"}}}, {"/something/secondthingaaaa/thirdthing", false, "/something/:paramname/thirdthing", Params{Param{Key: "paramname", Value: "secondthingaaaa"}}}, {"/something/se/thirdthing", false, "/something/:paramname/thirdthing", Params{Param{Key: "paramname", Value: "se"}}}, {"/something/s/thirdthing", false, "/something/:paramname/thirdthing", Params{Param{Key: "paramname", Value: "s"}}}, {"/c/d/ee", false, "/:cc/:dd/ee", Params{Param{Key: "cc", Value: "c"}, Param{Key: "dd", Value: "d"}}}, {"/c/d/e/ff", false, "/:cc/:dd/:ee/ff", Params{Param{Key: "cc", Value: "c"}, Param{Key: "dd", Value: "d"}, Param{Key: "ee", Value: "e"}}}, {"/c/d/e/f/gg", false, "/:cc/:dd/:ee/:ff/gg", Params{Param{Key: "cc", Value: "c"}, Param{Key: "dd", Value: "d"}, Param{Key: "ee", Value: "e"}, Param{Key: "ff", Value: "f"}}}, {"/c/d/e/f/g/hh", false, "/:cc/:dd/:ee/:ff/:gg/hh", Params{Param{Key: "cc", Value: "c"}, Param{Key: "dd", Value: "d"}, Param{Key: "ee", Value: "e"}, Param{Key: "ff", Value: "f"}, Param{Key: "gg", Value: "g"}}}, {"/cc/dd/ee/ff/gg/hh", false, "/:cc/:dd/:ee/:ff/:gg/hh", Params{Param{Key: "cc", Value: "cc"}, Param{Key: "dd", Value: "dd"}, Param{Key: "ee", Value: "ee"}, Param{Key: "ff", Value: "ff"}, Param{Key: "gg", Value: "gg"}}}, {"/get/abc", false, "/get/abc", nil}, {"/get/a", false, "/get/:param", Params{Param{Key: "param", Value: "a"}}}, {"/get/abz", false, "/get/:param", Params{Param{Key: "param", Value: "abz"}}}, {"/get/12a", false, "/get/:param", Params{Param{Key: "param", Value: "12a"}}}, {"/get/abcd", false, "/get/:param", Params{Param{Key: "param", Value: "abcd"}}}, {"/get/abc/123abc", false, "/get/abc/123abc", nil}, {"/get/abc/12", false, "/get/abc/:param", Params{Param{Key: "param", Value: "12"}}}, {"/get/abc/123ab", false, "/get/abc/:param", Params{Param{Key: "param", Value: "123ab"}}}, {"/get/abc/xyz", false, "/get/abc/:param", Params{Param{Key: "param", Value: "xyz"}}}, {"/get/abc/123abcddxx", false, "/get/abc/:param", Params{Param{Key: "param", Value: "123abcddxx"}}}, {"/get/abc/123abc/xxx8", false, "/get/abc/123abc/xxx8", nil}, {"/get/abc/123abc/x", false, "/get/abc/123abc/:param", Params{Param{Key: "param", Value: "x"}}}, {"/get/abc/123abc/xxx", false, "/get/abc/123abc/:param", Params{Param{Key: "param", Value: "xxx"}}}, {"/get/abc/123abc/abc", false, "/get/abc/123abc/:param", Params{Param{Key: "param", Value: "abc"}}}, {"/get/abc/123abc/xxx8xxas", false, "/get/abc/123abc/:param", Params{Param{Key: "param", Value: "xxx8xxas"}}}, {"/get/abc/123abc/xxx8/1234", false, "/get/abc/123abc/xxx8/1234", nil}, {"/get/abc/123abc/xxx8/1", false, "/get/abc/123abc/xxx8/:param", Params{Param{Key: "param", Value: "1"}}}, {"/get/abc/123abc/xxx8/123", false, "/get/abc/123abc/xxx8/:param", Params{Param{Key: "param", Value: "123"}}}, {"/get/abc/123abc/xxx8/78k", false, "/get/abc/123abc/xxx8/:param", Params{Param{Key: "param", Value: "78k"}}}, {"/get/abc/123abc/xxx8/1234xxxd", false, "/get/abc/123abc/xxx8/:param", Params{Param{Key: "param", Value: "1234xxxd"}}}, {"/get/abc/123abc/xxx8/1234/ffas", false, "/get/abc/123abc/xxx8/1234/ffas", nil}, {"/get/abc/123abc/xxx8/1234/f", false, "/get/abc/123abc/xxx8/1234/:param", Params{Param{Key: "param", Value: "f"}}}, {"/get/abc/123abc/xxx8/1234/ffa", false, "/get/abc/123abc/xxx8/1234/:param", Params{Param{Key: "param", Value: "ffa"}}}, {"/get/abc/123abc/xxx8/1234/kka", false, "/get/abc/123abc/xxx8/1234/:param", Params{Param{Key: "param", Value: "kka"}}}, {"/get/abc/123abc/xxx8/1234/ffas321", false, "/get/abc/123abc/xxx8/1234/:param", Params{Param{Key: "param", Value: "ffas321"}}}, {"/get/abc/123abc/xxx8/1234/kkdd/12c", false, "/get/abc/123abc/xxx8/1234/kkdd/12c", nil}, {"/get/abc/123abc/xxx8/1234/kkdd/1", false, "/get/abc/123abc/xxx8/1234/kkdd/:param", Params{Param{Key: "param", Value: "1"}}}, {"/get/abc/123abc/xxx8/1234/kkdd/12", false, "/get/abc/123abc/xxx8/1234/kkdd/:param", Params{Param{Key: "param", Value: "12"}}}, {"/get/abc/123abc/xxx8/1234/kkdd/12b", false, "/get/abc/123abc/xxx8/1234/kkdd/:param", Params{Param{Key: "param", Value: "12b"}}}, {"/get/abc/123abc/xxx8/1234/kkdd/34", false, "/get/abc/123abc/xxx8/1234/kkdd/:param", Params{Param{Key: "param", Value: "34"}}}, {"/get/abc/123abc/xxx8/1234/kkdd/12c2e3", false, "/get/abc/123abc/xxx8/1234/kkdd/:param", Params{Param{Key: "param", Value: "12c2e3"}}}, {"/get/abc/12/test", false, "/get/abc/:param/test", Params{Param{Key: "param", Value: "12"}}}, {"/get/abc/123abdd/test", false, "/get/abc/:param/test", Params{Param{Key: "param", Value: "123abdd"}}}, {"/get/abc/123abdddf/test", false, "/get/abc/:param/test", Params{Param{Key: "param", Value: "123abdddf"}}}, {"/get/abc/123ab/test", false, "/get/abc/:param/test", Params{Param{Key: "param", Value: "123ab"}}}, {"/get/abc/123abgg/test", false, "/get/abc/:param/test", Params{Param{Key: "param", Value: "123abgg"}}}, {"/get/abc/123abff/test", false, "/get/abc/:param/test", Params{Param{Key: "param", Value: "123abff"}}}, {"/get/abc/123abffff/test", false, "/get/abc/:param/test", Params{Param{Key: "param", Value: "123abffff"}}}, {"/get/abc/123abd/test", false, "/get/abc/123abd/:param", Params{Param{Key: "param", Value: "test"}}}, {"/get/abc/123abddd/test", false, "/get/abc/123abddd/:param", Params{Param{Key: "param", Value: "test"}}}, {"/get/abc/123/test22", false, "/get/abc/123/:param", Params{Param{Key: "param", Value: "test22"}}}, {"/get/abc/123abg/test", false, "/get/abc/123abg/:param", Params{Param{Key: "param", Value: "test"}}}, {"/get/abc/123abf/testss", false, "/get/abc/123abf/:param", Params{Param{Key: "param", Value: "testss"}}}, {"/get/abc/123abfff/te", false, "/get/abc/123abfff/:param", Params{Param{Key: "param", Value: "te"}}}, {"/get/abc/escaped_colon/test\\:param", false, "/get/abc/escaped_colon/test\\:param", nil}, }) checkPriorities(t, tree) } func TestUnescapeParameters(t *testing.T) { tree := &node{} routes := [...]string{ "/", "/cmd/:tool/:sub", "/cmd/:tool/", "/src/*filepath", "/search/:query", "/files/:dir/*filepath", "/info/:user/project/:project", "/info/:user", } for _, route := range routes { tree.addRoute(route, fakeHandler(route)) } unescape := true checkRequests(t, tree, testRequests{ {"/", false, "/", nil}, {"/cmd/test/", false, "/cmd/:tool/", Params{Param{Key: "tool", Value: "test"}}}, {"/cmd/test", true, "", Params{Param{Key: "tool", Value: "test"}}}, {"/src/some/file.png", false, "/src/*filepath", Params{Param{Key: "filepath", Value: "/some/file.png"}}}, {"/src/some/file+test.png", false, "/src/*filepath", Params{Param{Key: "filepath", Value: "/some/file test.png"}}}, {"/src/some/file++++%%%%test.png", false, "/src/*filepath", Params{Param{Key: "filepath", Value: "/some/file++++%%%%test.png"}}}, {"/src/some/file%2Ftest.png", false, "/src/*filepath", Params{Param{Key: "filepath", Value: "/some/file/test.png"}}}, {"/search/someth!ng+in+ΓΌnΓ¬codΓ©", false, "/search/:query", Params{Param{Key: "query", Value: "someth!ng in ΓΌnΓ¬codΓ©"}}}, {"/info/gordon/project/go", false, "/info/:user/project/:project", Params{Param{Key: "user", Value: "gordon"}, Param{Key: "project", Value: "go"}}}, {"/info/slash%2Fgordon", false, "/info/:user", Params{Param{Key: "user", Value: "slash/gordon"}}}, {"/info/slash%2Fgordon/project/Project%20%231", false, "/info/:user/project/:project", Params{Param{Key: "user", Value: "slash/gordon"}, Param{Key: "project", Value: "Project #1"}}}, {"/info/slash%%%%", false, "/info/:user", Params{Param{Key: "user", Value: "slash%%%%"}}}, {"/info/slash%%%%2Fgordon/project/Project%%%%20%231", false, "/info/:user/project/:project", Params{Param{Key: "user", Value: "slash%%%%2Fgordon"}, Param{Key: "project", Value: "Project%%%%20%231"}}}, }, unescape) checkPriorities(t, tree) } func catchPanic(testFunc func()) (recv any) { defer func() { recv = recover() }() testFunc() return } type testRoute struct { path string conflict bool } func testRoutes(t *testing.T, routes []testRoute) { tree := &node{} for _, route := range routes { recv := catchPanic(func() { tree.addRoute(route.path, nil) }) if route.conflict { if recv == nil { t.Errorf("no panic for conflicting route '%s'", route.path) } } else if recv != nil { t.Errorf("unexpected panic for route '%s': %v", route.path, recv) } } } func TestTreeWildcardConflict(t *testing.T) { routes := []testRoute{ {"/cmd/:tool/:sub", false}, {"/cmd/vet", false}, {"/foo/bar", false}, {"/foo/:name", false}, {"/foo/:names", true}, {"/cmd/*path", true}, {"/cmd/:badvar", true}, {"/cmd/:tool/names", false}, {"/cmd/:tool/:badsub/details", true}, {"/src/*filepath", false}, {"/src/:file", true}, {"/src/static.json", true}, {"/src/*filepathx", true}, {"/src/", true}, {"/src/foo/bar", true}, {"/src1/", false}, {"/src1/*filepath", true}, {"/src2*filepath", true}, {"/src2/*filepath", false}, {"/search/:query", false}, {"/search/valid", false}, {"/user_:name", false}, {"/user_x", false}, {"/user_:name", false}, {"/id:id", false}, {"/id/:id", false}, {"/static/*file", false}, {"/static/", true}, {"/escape/test\\:d1", false}, {"/escape/test\\:d2", false}, {"/escape/test:param", false}, } testRoutes(t, routes) } func TestCatchAllAfterSlash(t *testing.T) { routes := []testRoute{ {"/non-leading-*catchall", true}, } testRoutes(t, routes) } func TestTreeChildConflict(t *testing.T) { routes := []testRoute{ {"/cmd/vet", false}, {"/cmd/:tool", false}, {"/cmd/:tool/:sub", false}, {"/cmd/:tool/misc", false}, {"/cmd/:tool/:othersub", true}, {"/src/AUTHORS", false}, {"/src/*filepath", true}, {"/user_x", false}, {"/user_:name", false}, {"/id/:id", false}, {"/id:id", false}, {"/:id", false}, {"/*filepath", true}, } testRoutes(t, routes) } func TestTreeDuplicatePath(t *testing.T) { tree := &node{} routes := [...]string{ "/", "/doc/", "/src/*filepath", "/search/:query", "/user_:name", } for _, route := range routes { recv := catchPanic(func() { tree.addRoute(route, fakeHandler(route)) }) if recv != nil { t.Fatalf("panic inserting route '%s': %v", route, recv) } // Add again recv = catchPanic(func() { tree.addRoute(route, nil) }) if recv == nil { t.Fatalf("no panic while inserting duplicate route '%s", route) } } // printChildren(tree, "") checkRequests(t, tree, testRequests{ {"/", false, "/", nil}, {"/doc/", false, "/doc/", nil}, {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}}, {"/search/someth!ng+in+ΓΌnΓ¬codΓ©", false, "/search/:query", Params{Param{"query", "someth!ng+in+ΓΌnΓ¬codΓ©"}}}, {"/user_gopher", false, "/user_:name", Params{Param{"name", "gopher"}}}, }) } func TestEmptyWildcardName(t *testing.T) { tree := &node{} routes := [...]string{ "/user:", "/user:/", "/cmd/:/", "/src/*", } for _, route := range routes { recv := catchPanic(func() { tree.addRoute(route, nil) }) if recv == nil { t.Fatalf("no panic while inserting route with empty wildcard name '%s", route) } } } func TestTreeCatchAllConflict(t *testing.T) { routes := []testRoute{ {"/src/*filepath/x", true}, {"/src2/", false}, {"/src2/*filepath/x", true}, {"/src3/*filepath", false}, {"/src3/*filepath/x", true}, } testRoutes(t, routes) } func TestTreeCatchAllConflictRoot(t *testing.T) { routes := []testRoute{ {"/", false}, {"/*filepath", true}, } testRoutes(t, routes) } func TestTreeCatchMaxParams(t *testing.T) { tree := &node{} route := "/cmd/*filepath" tree.addRoute(route, fakeHandler(route)) } func TestTreeDoubleWildcard(t *testing.T) { const panicMsg = "only one wildcard per path segment is allowed" routes := [...]string{ "/:foo:bar", "/:foo:bar/", "/:foo*bar", } for _, route := range routes { tree := &node{} recv := catchPanic(func() { tree.addRoute(route, nil) }) if rs, ok := recv.(string); !ok || !strings.HasPrefix(rs, panicMsg) { t.Fatalf(`"Expected panic "%s" for route '%s', got "%v"`, panicMsg, route, recv) } } } /*func TestTreeDuplicateWildcard(t *testing.T) { tree := &node{} routes := [...]string{ "/:id/:name/:id", } for _, route := range routes { ... } }*/ func TestTreeTrailingSlashRedirect(t *testing.T) { tree := &node{} routes := [...]string{ "/hi", "/b/", "/search/:query", "/cmd/:tool/", "/src/*filepath", "/x", "/x/y", "/y/", "/y/z", "/0/:id", "/0/:id/1", "/1/:id/", "/1/:id/2", "/aa", "/a/", "/admin", "/admin/:category", "/admin/:category/:page", "/doc", "/doc/go_faq.html", "/doc/go1.html", "/no/a", "/no/b", "/api/:page/:name", "/api/hello/:name/bar/", "/api/bar/:name", "/api/baz/foo", "/api/baz/foo/bar", "/blog/:p", "/posts/:b/:c", "/posts/b/:c/d/", "/vendor/:x/*y", } for _, route := range routes { recv := catchPanic(func() { tree.addRoute(route, fakeHandler(route)) }) if recv != nil { t.Fatalf("panic inserting route '%s': %v", route, recv) } } tsrRoutes := [...]string{ "/hi/", "/b", "/search/gopher/", "/cmd/vet", "/src", "/x/", "/y", "/0/go/", "/1/go", "/a", "/admin/", "/admin/config/", "/admin/config/permissions/", "/doc/", "/admin/static/", "/admin/cfg/", "/admin/cfg/users/", "/api/hello/x/bar", "/api/baz/foo/", "/api/baz/bax/", "/api/bar/huh/", "/api/baz/foo/bar/", "/api/world/abc/", "/blog/pp/", "/posts/b/c/d", "/vendor/x", } for _, route := range tsrRoutes { value := tree.getValue(route, nil, getSkippedNodes(), false) if value.handlers != nil { t.Fatalf("non-nil handler for TSR route '%s", route) } else if !value.tsr { t.Errorf("expected TSR recommendation for route '%s'", route) } } noTsrRoutes := [...]string{ "/", "/no", "/no/", "/_", "/_/", "/api", "/api/", "/api/hello/x/foo", "/api/baz/foo/bad", "/foo/p/p", } for _, route := range noTsrRoutes { value := tree.getValue(route, nil, getSkippedNodes(), false) if value.handlers != nil { t.Fatalf("non-nil handler for No-TSR route '%s", route) } else if value.tsr { t.Errorf("expected no TSR recommendation for route '%s'", route) } } } func TestTreeRootTrailingSlashRedirect(t *testing.T) { tree := &node{} recv := catchPanic(func() { tree.addRoute("/:test", fakeHandler("/:test")) }) if recv != nil { t.Fatalf("panic inserting test route: %v", recv) } value := tree.getValue("/", nil, getSkippedNodes(), false) if value.handlers != nil { t.Fatalf("non-nil handler") } else if value.tsr { t.Errorf("expected no TSR recommendation") } } func TestRedirectTrailingSlash(t *testing.T) { data := []struct { path string }{ {"/hello/:name"}, {"/hello/:name/123"}, {"/hello/:name/234"}, } node := &node{} for _, item := range data { node.addRoute(item.path, fakeHandler("test")) } value := node.getValue("/hello/abx/", nil, getSkippedNodes(), false) if value.tsr != true { t.Fatalf("want true, is false") } } func TestTreeFindCaseInsensitivePath(t *testing.T) { tree := &node{} longPath := "/l" + strings.Repeat("o", 128) + "ng" lOngPath := "/l" + strings.Repeat("O", 128) + "ng/" routes := [...]string{ "/hi", "/b/", "/ABC/", "/search/:query", "/cmd/:tool/", "/src/*filepath", "/x", "/x/y", "/y/", "/y/z", "/0/:id", "/0/:id/1", "/1/:id/", "/1/:id/2", "/aa", "/a/", "/doc", "/doc/go_faq.html", "/doc/go1.html", "/doc/go/away", "/no/a", "/no/b", "/Ξ ", "/u/apfΓͺl/", "/u/Γ€pfΓͺl/", "/u/ΓΆpfΓͺl", "/v/Γ„pfΓͺl/", "/v/Γ–pfΓͺl", "/w/♬", // 3 byte "/w/β™­/", // 3 byte, last byte differs "/w/𠜎", // 4 byte "/w/𠜏/", // 4 byte longPath, } for _, route := range routes { recv := catchPanic(func() { tree.addRoute(route, fakeHandler(route)) }) if recv != nil { t.Fatalf("panic inserting route '%s': %v", route, recv) } } // Check out == in for all registered routes // With fixTrailingSlash = true for _, route := range routes { out, found := tree.findCaseInsensitivePath(route, true) if !found { t.Errorf("Route '%s' not found!", route) } else if string(out) != route { t.Errorf("Wrong result for route '%s': %s", route, string(out)) } } // With fixTrailingSlash = false for _, route := range routes { out, found := tree.findCaseInsensitivePath(route, false) if !found { t.Errorf("Route '%s' not found!", route) } else if string(out) != route { t.Errorf("Wrong result for route '%s': %s", route, string(out)) } } tests := []struct { in string out string found bool slash bool }{ {"/HI", "/hi", true, false}, {"/HI/", "/hi", true, true}, {"/B", "/b/", true, true}, {"/B/", "/b/", true, false}, {"/abc", "/ABC/", true, true}, {"/abc/", "/ABC/", true, false}, {"/aBc", "/ABC/", true, true}, {"/aBc/", "/ABC/", true, false}, {"/abC", "/ABC/", true, true}, {"/abC/", "/ABC/", true, false}, {"/SEARCH/QUERY", "/search/QUERY", true, false}, {"/SEARCH/QUERY/", "/search/QUERY", true, true}, {"/CMD/TOOL/", "/cmd/TOOL/", true, false}, {"/CMD/TOOL", "/cmd/TOOL/", true, true}, {"/SRC/FILE/PATH", "/src/FILE/PATH", true, false}, {"/x/Y", "/x/y", true, false}, {"/x/Y/", "/x/y", true, true}, {"/X/y", "/x/y", true, false}, {"/X/y/", "/x/y", true, true}, {"/X/Y", "/x/y", true, false}, {"/X/Y/", "/x/y", true, true}, {"/Y/", "/y/", true, false}, {"/Y", "/y/", true, true}, {"/Y/z", "/y/z", true, false}, {"/Y/z/", "/y/z", true, true}, {"/Y/Z", "/y/z", true, false}, {"/Y/Z/", "/y/z", true, true}, {"/y/Z", "/y/z", true, false}, {"/y/Z/", "/y/z", true, true}, {"/Aa", "/aa", true, false}, {"/Aa/", "/aa", true, true}, {"/AA", "/aa", true, false}, {"/AA/", "/aa", true, true}, {"/aA", "/aa", true, false}, {"/aA/", "/aa", true, true}, {"/A/", "/a/", true, false}, {"/A", "/a/", true, true}, {"/DOC", "/doc", true, false}, {"/DOC/", "/doc", true, true}, {"/NO", "", false, true}, {"/DOC/GO", "", false, true}, {"/Ο€", "/Ξ ", true, false}, {"/Ο€/", "/Ξ ", true, true}, {"/u/Γ„PFÊL/", "/u/Γ€pfΓͺl/", true, false}, {"/u/Γ„PFÊL", "/u/Γ€pfΓͺl/", true, true}, {"/u/Γ–PFÊL/", "/u/ΓΆpfΓͺl", true, true}, {"/u/Γ–PFÊL", "/u/ΓΆpfΓͺl", true, false}, {"/v/Γ€pfΓͺL/", "/v/Γ„pfΓͺl/", true, false}, {"/v/Γ€pfΓͺL", "/v/Γ„pfΓͺl/", true, true}, {"/v/ΓΆpfΓͺL/", "/v/Γ–pfΓͺl", true, true}, {"/v/ΓΆpfΓͺL", "/v/Γ–pfΓͺl", true, false}, {"/w/♬/", "/w/♬", true, true}, {"/w/β™­", "/w/β™­/", true, true}, {"/w/𠜎/", "/w/𠜎", true, true}, {"/w/𠜏", "/w/𠜏/", true, true}, {lOngPath, longPath, true, true}, } // With fixTrailingSlash = true for _, test := range tests { out, found := tree.findCaseInsensitivePath(test.in, true) if found != test.found || (found && (string(out) != test.out)) { t.Errorf("Wrong result for '%s': got %s, %t; want %s, %t", test.in, string(out), found, test.out, test.found) return } } // With fixTrailingSlash = false for _, test := range tests { out, found := tree.findCaseInsensitivePath(test.in, false) if test.slash { if found { // test needs a trailingSlash fix. It must not be found! t.Errorf("Found without fixTrailingSlash: %s; got %s", test.in, string(out)) } } else { if found != test.found || (found && (string(out) != test.out)) { t.Errorf("Wrong result for '%s': got %s, %t; want %s, %t", test.in, string(out), found, test.out, test.found) return } } } } func TestTreeInvalidNodeType(t *testing.T) { const panicMsg = "invalid node type" tree := &node{} tree.addRoute("/", fakeHandler("/")) tree.addRoute("/:page", fakeHandler("/:page")) // set invalid node type tree.children[0].nType = 42 // normal lookup recv := catchPanic(func() { tree.getValue("/test", nil, getSkippedNodes(), false) }) if rs, ok := recv.(string); !ok || rs != panicMsg { t.Fatalf("Expected panic '"+panicMsg+"', got '%v'", recv) } // case-insensitive lookup recv = catchPanic(func() { tree.findCaseInsensitivePath("/test", true) }) if rs, ok := recv.(string); !ok || rs != panicMsg { t.Fatalf("Expected panic '"+panicMsg+"', got '%v'", recv) } } func TestTreeInvalidParamsType(t *testing.T) { tree := &node{} // add a child with wildcard route := "/:path" tree.addRoute(route, fakeHandler(route)) // set invalid Params type params := make(Params, 0) // try to trigger slice bounds out of range with capacity 0 tree.getValue("/test", &params, getSkippedNodes(), false) } func TestTreeExpandParamsCapacity(t *testing.T) { data := []struct { path string }{ {"/:path"}, {"/*path"}, } for _, item := range data { tree := &node{} tree.addRoute(item.path, fakeHandler(item.path)) params := make(Params, 0) value := tree.getValue("/test", &params, getSkippedNodes(), false) if value.params == nil { t.Errorf("Expected %s params to be set, but they weren't", item.path) continue } if len(*value.params) != 1 { t.Errorf("Wrong number of %s params: got %d, want %d", item.path, len(*value.params), 1) continue } } } func TestTreeWildcardConflictEx(t *testing.T) { conflicts := [...]struct { route string segPath string existPath string existSegPath string }{ {"/who/are/foo", "/foo", `/who/are/\*you`, `/\*you`}, {"/who/are/foo/", "/foo/", `/who/are/\*you`, `/\*you`}, {"/who/are/foo/bar", "/foo/bar", `/who/are/\*you`, `/\*you`}, {"/con:nection", ":nection", `/con:tact`, `:tact`}, } for _, conflict := range conflicts { // I have to re-create a 'tree', because the 'tree' will be // in an inconsistent state when the loop recovers from the // panic which threw by 'addRoute' function. tree := &node{} routes := [...]string{ "/con:tact", "/who/are/*you", "/who/foo/hello", } for _, route := range routes { tree.addRoute(route, fakeHandler(route)) } recv := catchPanic(func() { tree.addRoute(conflict.route, fakeHandler(conflict.route)) }) if !regexp.MustCompile(fmt.Sprintf("'%s' in new path .* conflicts with existing wildcard '%s' in existing prefix '%s'", conflict.segPath, conflict.existSegPath, conflict.existPath)).MatchString(fmt.Sprint(recv)) { t.Fatalf("invalid wildcard conflict error (%v)", recv) } } } func TestTreeInvalidEscape(t *testing.T) { routes := map[string]bool{ "/r1/r": true, "/r2/:r": true, "/r3/\\:r": true, } tree := &node{} for route, valid := range routes { recv := catchPanic(func() { tree.addRoute(route, fakeHandler(route)) }) if recv == nil != valid { t.Fatalf("%s should be %t but got %v", route, valid, recv) } } } func TestWildcardInvalidSlash(t *testing.T) { const panicMsgPrefix = "no / before catch-all in path" routes := map[string]bool{ "/foo/bar": true, "/foo/x*zy": false, "/foo/b*r": false, } for route, valid := range routes { tree := &node{} recv := catchPanic(func() { tree.addRoute(route, nil) }) if recv == nil != valid { t.Fatalf("%s should be %t but got %v", route, valid, recv) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
true
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/mode_test.go
mode_test.go
// 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 gin import ( "os" "sync/atomic" "testing" "github.com/gin-gonic/gin/binding" "github.com/stretchr/testify/assert" ) func init() { os.Setenv(EnvGinMode, TestMode) } func TestSetMode(t *testing.T) { assert.Equal(t, int32(testCode), atomic.LoadInt32(&ginMode)) assert.Equal(t, TestMode, Mode()) os.Unsetenv(EnvGinMode) SetMode("") assert.Equal(t, int32(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.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") }) } func TestDisableBindValidation(t *testing.T) { v := binding.Validator assert.NotNil(t, binding.Validator) DisableBindValidation() assert.Nil(t, binding.Validator) binding.Validator = v } func TestEnableJsonDecoderUseNumber(t *testing.T) { assert.False(t, binding.EnableDecoderUseNumber) EnableJsonDecoderUseNumber() assert.True(t, binding.EnableDecoderUseNumber) } func TestEnableJsonDecoderDisallowUnknownFields(t *testing.T) { assert.False(t, binding.EnableDecoderDisallowUnknownFields) EnableJsonDecoderDisallowUnknownFields() assert.True(t, binding.EnableDecoderDisallowUnknownFields) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/auth_test.go
auth_test.go
// 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 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", }) assert.Len(t, pairs, 3) assert.Contains(t, pairs, authPair{ user: "bar", value: "Basic YmFyOmZvbw==", }) assert.Contains(t, pairs, authPair{ user: "foo", value: "Basic Zm9vOmJhcg==", }) assert.Contains(t, pairs, authPair{ user: "admin", value: "Basic YWRtaW46cGFzc3dvcmQ=", }) } func TestBasicAuthFails(t *testing.T) { assert.Panics(t, func() { processAccounts(nil) }) assert.Panics(t, func() { processAccounts(Accounts{ "": "password", "foo": "bar", }) }) } func TestBasicAuthSearchCredential(t *testing.T) { pairs := processAccounts(Accounts{ "admin": "password", "foo": "bar", "bar": "foo", }) user, found := pairs.searchCredential(authorizationHeader("admin", "password")) assert.Equal(t, "admin", user) assert.True(t, found) user, found = pairs.searchCredential(authorizationHeader("foo", "bar")) assert.Equal(t, "foo", user) assert.True(t, found) user, found = pairs.searchCredential(authorizationHeader("bar", "foo")) assert.Equal(t, "bar", user) assert.True(t, found) user, found = pairs.searchCredential(authorizationHeader("admins", "password")) assert.Empty(t, user) assert.False(t, found) user, found = pairs.searchCredential(authorizationHeader("foo", "bar ")) assert.Empty(t, user) assert.False(t, found) user, found = pairs.searchCredential("") assert.Empty(t, user) assert.False(t, found) } func TestBasicAuthAuthorizationHeader(t *testing.T) { assert.Equal(t, "Basic YWRtaW46cGFzc3dvcmQ=", authorizationHeader("admin", "password")) } func TestBasicAuthSucceed(t *testing.T) { accounts := Accounts{"admin": "password"} router := New() router.Use(BasicAuth(accounts)) router.GET("/login", func(c *Context) { c.String(http.StatusOK, c.MustGet(AuthUserKey).(string)) }) w := httptest.NewRecorder() req, _ := http.NewRequest(http.MethodGet, "/login", nil) req.Header.Set("Authorization", authorizationHeader("admin", "password")) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "admin", w.Body.String()) } func TestBasicAuth401(t *testing.T) { called := false accounts := Accounts{"foo": "bar"} router := New() router.Use(BasicAuth(accounts)) router.GET("/login", func(c *Context) { called = true c.String(http.StatusOK, c.MustGet(AuthUserKey).(string)) }) w := httptest.NewRecorder() req, _ := http.NewRequest(http.MethodGet, "/login", nil) req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password"))) router.ServeHTTP(w, req) assert.False(t, called) assert.Equal(t, http.StatusUnauthorized, w.Code) assert.Equal(t, "Basic realm=\"Authorization Required\"", w.Header().Get("WWW-Authenticate")) } func TestBasicAuth401WithCustomRealm(t *testing.T) { called := false accounts := Accounts{"foo": "bar"} router := New() router.Use(BasicAuthForRealm(accounts, "My Custom \"Realm\"")) router.GET("/login", func(c *Context) { called = true c.String(http.StatusOK, c.MustGet(AuthUserKey).(string)) }) w := httptest.NewRecorder() req, _ := http.NewRequest(http.MethodGet, "/login", nil) req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password"))) router.ServeHTTP(w, req) assert.False(t, called) assert.Equal(t, http.StatusUnauthorized, w.Code) assert.Equal(t, "Basic realm=\"My Custom \\\"Realm\\\"\"", w.Header().Get("WWW-Authenticate")) } func TestBasicAuthForProxySucceed(t *testing.T) { accounts := Accounts{"admin": "password"} router := New() router.Use(BasicAuthForProxy(accounts, "")) router.Any("/*proxyPath", func(c *Context) { c.String(http.StatusOK, c.MustGet(AuthProxyUserKey).(string)) }) w := httptest.NewRecorder() req, _ := http.NewRequest(http.MethodGet, "/test", nil) req.Header.Set("Proxy-Authorization", authorizationHeader("admin", "password")) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "admin", w.Body.String()) } func TestBasicAuthForProxy407(t *testing.T) { called := false accounts := Accounts{"foo": "bar"} router := New() router.Use(BasicAuthForProxy(accounts, "")) router.Any("/*proxyPath", func(c *Context) { called = true c.String(http.StatusOK, c.MustGet(AuthProxyUserKey).(string)) }) w := httptest.NewRecorder() req, _ := http.NewRequest(http.MethodGet, "/test", nil) req.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("admin:password"))) router.ServeHTTP(w, req) assert.False(t, called) assert.Equal(t, http.StatusProxyAuthRequired, w.Code) assert.Equal(t, "Basic realm=\"Proxy Authorization Required\"", w.Header().Get("Proxy-Authenticate")) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/codec/json/json.go
codec/json/json.go
// 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. //go:build !jsoniter && !go_json && !(sonic && (linux || windows || darwin)) package json import ( "encoding/json" "io" ) // Package indicates what library is being used for JSON encoding. const Package = "encoding/json" func init() { API = jsonApi{} } type jsonApi struct{} func (j jsonApi) Marshal(v any) ([]byte, error) { return json.Marshal(v) } func (j jsonApi) Unmarshal(data []byte, v any) error { return json.Unmarshal(data, v) } func (j jsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) { return json.MarshalIndent(v, prefix, indent) } func (j jsonApi) NewEncoder(writer io.Writer) Encoder { return json.NewEncoder(writer) } func (j jsonApi) NewDecoder(reader io.Reader) Decoder { return json.NewDecoder(reader) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/codec/json/api.go
codec/json/api.go
// 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 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) error MarshalIndent(v any, prefix, indent string) ([]byte, error) NewEncoder(writer io.Writer) Encoder NewDecoder(reader io.Reader) Decoder } // Encoder an interface writes JSON values to 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, and \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 bool) // Encode writes the JSON encoding of v to the stream, // followed by a newline character. // // See the documentation for Marshal for details about the // conversion of Go values to JSON. Encode(v any) error } // Decoder an interface reads and decodes JSON values from an input stream. type Decoder interface { // UseNumber causes the Decoder to unmarshal a number into an any as a // Number instead of as a float64. UseNumber() // DisallowUnknownFields causes the Decoder to return an error when the destination // is a struct and the input contains object keys which do not match any // non-ignored, exported fields in the destination. DisallowUnknownFields() // Decode reads the next JSON-encoded value from its // input and stores it in the value pointed to by v. // // See the documentation for Unmarshal for details about // the conversion of JSON into a Go value. Decode(v any) error }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/codec/json/jsoniter.go
codec/json/jsoniter.go
// 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. //go:build jsoniter package json import ( "io" jsoniter "github.com/json-iterator/go" ) // Package indicates what library is being used for JSON encoding. const Package = "github.com/json-iterator/go" func init() { API = jsoniterApi{} } var json = jsoniter.ConfigCompatibleWithStandardLibrary type jsoniterApi struct{} func (j jsoniterApi) Marshal(v any) ([]byte, error) { return json.Marshal(v) } func (j jsoniterApi) Unmarshal(data []byte, v any) error { return json.Unmarshal(data, v) } func (j jsoniterApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) { return json.MarshalIndent(v, prefix, indent) } func (j jsoniterApi) NewEncoder(writer io.Writer) Encoder { return json.NewEncoder(writer) } func (j jsoniterApi) NewDecoder(reader io.Reader) Decoder { return json.NewDecoder(reader) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/codec/json/sonic.go
codec/json/sonic.go
// 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. //go:build sonic && (linux || windows || darwin) package json import ( "io" "github.com/bytedance/sonic" ) // Package indicates what library is being used for JSON encoding. const Package = "github.com/bytedance/sonic" func init() { API = sonicApi{} } var json = sonic.ConfigStd type sonicApi struct{} func (j sonicApi) Marshal(v any) ([]byte, error) { return json.Marshal(v) } func (j sonicApi) Unmarshal(data []byte, v any) error { return json.Unmarshal(data, v) } func (j sonicApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) { return json.MarshalIndent(v, prefix, indent) } func (j sonicApi) NewEncoder(writer io.Writer) Encoder { return json.NewEncoder(writer) } func (j sonicApi) NewDecoder(reader io.Reader) Decoder { return json.NewDecoder(reader) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/codec/json/go_json.go
codec/json/go_json.go
// 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. //go:build go_json package json import ( "io" "github.com/goccy/go-json" ) // Package indicates what library is being used for JSON encoding. const Package = "github.com/goccy/go-json" func init() { API = gojsonApi{} } type gojsonApi struct{} func (j gojsonApi) Marshal(v any) ([]byte, error) { return json.Marshal(v) } func (j gojsonApi) Unmarshal(data []byte, v any) error { return json.Unmarshal(data, v) } func (j gojsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) { return json.MarshalIndent(v, prefix, indent) } func (j gojsonApi) NewEncoder(writer io.Writer) Encoder { return json.NewEncoder(writer) } func (j gojsonApi) NewDecoder(reader io.Reader) Decoder { return json.NewDecoder(reader) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/ginS/gins.go
ginS/gins.go
// 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 ginS import ( "html/template" "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 LoadHTMLFiles(files ...string) { engine().LoadHTMLFiles(files...) } // LoadHTMLFS is a wrapper for Engine.LoadHTMLFS. func LoadHTMLFS(fs http.FileSystem, patterns ...string) { engine().LoadHTMLFS(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 by 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 should add all the routes that have common middlewares or the same path prefix. // For example, all the routes that use a common middleware for authorization could be grouped. func Group(relativePath string, handlers ...gin.HandlerFunc) *gin.RouterGroup { return engine().Group(relativePath, handlers...) } // Handle is a wrapper for Engine.Handle. func Handle(httpMethod, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().Handle(httpMethod, relativePath, handlers...) } // POST is a shortcut for router.Handle("POST", path, handle) func POST(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().POST(relativePath, handlers...) } // GET is a shortcut for router.Handle("GET", path, handle) func GET(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().GET(relativePath, handlers...) } // DELETE is a shortcut for router.Handle("DELETE", path, handle) func DELETE(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().DELETE(relativePath, handlers...) } // PATCH is a shortcut for router.Handle("PATCH", path, handle) func PATCH(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().PATCH(relativePath, handlers...) } // PUT is a shortcut for router.Handle("PUT", path, handle) func PUT(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().PUT(relativePath, handlers...) } // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle) func OPTIONS(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().OPTIONS(relativePath, handlers...) } // HEAD is a shortcut for router.Handle("HEAD", path, handle) func HEAD(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().HEAD(relativePath, handlers...) } // Any is a wrapper for Engine.Any. func Any(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().Any(relativePath, handlers...) } // StaticFile is a wrapper for Engine.StaticFile. func StaticFile(relativePath, filepath string) gin.IRoutes { return engine().StaticFile(relativePath, filepath) } // Static serves files from the given file system root. // Internally a http.FileServer is used, therefore http.NotFound is used instead // of the Router's NotFound handler. // To use the operating system's file system implementation, // use : // // router.Static("/static", "/var/www") func Static(relativePath, root string) gin.IRoutes { return engine().Static(relativePath, root) } // StaticFS is a wrapper for Engine.StaticFS. func StaticFS(relativePath string, fs http.FileSystem) gin.IRoutes { return engine().StaticFS(relativePath, fs) } // Use attaches a global middleware to the router. i.e. the middlewares attached through Use() will be // included in the handlers chain for every single request. Even 404, 405, static files... // For example, this is the right place for a logger or error management middleware. func Use(middlewares ...gin.HandlerFunc) gin.IRoutes { return engine().Use(middlewares...) } // Routes returns a slice of registered routes. func Routes() gin.RoutesInfo { return engine().Routes() } // Run attaches to a http.Server and starts listening and serving HTTP requests. // It is a shortcut for http.ListenAndServe(addr, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func Run(addr ...string) (err error) { return engine().Run(addr...) } // RunTLS attaches to a http.Server and starts listening and serving HTTPS requests. // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. func RunTLS(addr, certFile, keyFile string) (err error) { return engine().RunTLS(addr, certFile, keyFile) } // RunUnix attaches to a http.Server and starts listening and serving HTTP requests // through the specified unix socket (i.e. a file) // Note: this method will block the calling goroutine indefinitely unless an error happens. func RunUnix(file string) (err error) { return engine().RunUnix(file) } // RunFd attaches the router to a http.Server and starts listening and serving HTTP requests // through the specified file descriptor. // Note: the method will block the calling goroutine indefinitely unless an error happens. func RunFd(fd int) (err error) { return engine().RunFd(fd) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/ginS/gins_test.go
ginS/gins_test.go
// 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 ginS import ( "html/template" "net/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 := httptest.NewRecorder() engine().ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "test", w.Body.String()) } func TestPOST(t *testing.T) { POST("/post", func(c *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) assert.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(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "updated", w.Body.String()) } func TestDELETE(t *testing.T) { DELETE("/delete", func(c *gin.Context) { c.String(http.StatusOK, "deleted") }) req := httptest.NewRequest(http.MethodDelete, "/delete", nil) w := httptest.NewRecorder() engine().ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "deleted", w.Body.String()) } func TestPATCH(t *testing.T) { PATCH("/patch", func(c *gin.Context) { c.String(http.StatusOK, "patched") }) req := httptest.NewRequest(http.MethodPatch, "/patch", nil) w := httptest.NewRecorder() engine().ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "patched", w.Body.String()) } func TestOPTIONS(t *testing.T) { OPTIONS("/options", func(c *gin.Context) { c.String(http.StatusOK, "options") }) req := httptest.NewRequest(http.MethodOptions, "/options", nil) w := httptest.NewRecorder() engine().ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "options", w.Body.String()) } func TestHEAD(t *testing.T) { HEAD("/head", func(c *gin.Context) { c.String(http.StatusOK, "head") }) req := httptest.NewRequest(http.MethodHead, "/head", nil) w := httptest.NewRecorder() engine().ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) } func TestAny(t *testing.T) { Any("/any", func(c *gin.Context) { c.String(http.StatusOK, "any") }) req := httptest.NewRequest(http.MethodGet, "/any", nil) w := httptest.NewRecorder() engine().ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "any", w.Body.String()) } func TestHandle(t *testing.T) { Handle(http.MethodGet, "/handle", func(c *gin.Context) { c.String(http.StatusOK, "handle") }) req := httptest.NewRequest(http.MethodGet, "/handle", nil) w := httptest.NewRecorder() engine().ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "handle", w.Body.String()) } func TestGroup(t *testing.T) { group := Group("/group") group.GET("/test", func(c *gin.Context) { c.String(http.StatusOK, "group test") }) req := httptest.NewRequest(http.MethodGet, "/group/test", nil) w := httptest.NewRecorder() engine().ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "group test", w.Body.String()) } func TestUse(t *testing.T) { var middlewareExecuted bool Use(func(c *gin.Context) { middlewareExecuted = true c.Next() }) GET("/middleware-test", func(c *gin.Context) { c.String(http.StatusOK, "ok") }) req := httptest.NewRequest(http.MethodGet, "/middleware-test", nil) w := httptest.NewRecorder() engine().ServeHTTP(w, req) assert.True(t, middlewareExecuted) assert.Equal(t, http.StatusOK, w.Code) } func TestNoRoute(t *testing.T) { NoRoute(func(c *gin.Context) { c.String(http.StatusNotFound, "custom 404") }) req := httptest.NewRequest(http.MethodGet, "/nonexistent", nil) w := httptest.NewRecorder() engine().ServeHTTP(w, req) assert.Equal(t, http.StatusNotFound, w.Code) assert.Equal(t, "custom 404", w.Body.String()) } func TestNoMethod(t *testing.T) { NoMethod(func(c *gin.Context) { c.String(http.StatusMethodNotAllowed, "method not allowed") }) // This just verifies that NoMethod is callable // Testing the actual behavior would require a separate engine instance assert.NotNil(t, engine()) } func TestRoutes(t *testing.T) { GET("/routes-test", func(c *gin.Context) {}) routes := Routes() assert.NotEmpty(t, routes) found := false for _, route := range routes { if route.Path == "/routes-test" && route.Method == http.MethodGet { found = true break } } assert.True(t, found) } func TestSetHTMLTemplate(t *testing.T) { tmpl := template.Must(template.New("test").Parse("Hello {{.}}")) SetHTMLTemplate(tmpl) // Verify engine has template set assert.NotNil(t, engine()) } func TestStaticFile(t *testing.T) { StaticFile("/static-file", "../testdata/test_file.txt") req := httptest.NewRequest(http.MethodGet, "/static-file", nil) w := httptest.NewRecorder() engine().ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) } func TestStatic(t *testing.T) { Static("/static-dir", "../testdata") req := httptest.NewRequest(http.MethodGet, "/static-dir/test_file.txt", nil) w := httptest.NewRecorder() engine().ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) } func TestStaticFS(t *testing.T) { fs := http.Dir("../testdata") StaticFS("/static-fs", fs) req := httptest.NewRequest(http.MethodGet, "/static-fs/test_file.txt", nil) w := httptest.NewRecorder() engine().ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/internal/bytesconv/bytesconv_test.go
internal/bytesconv/bytesconv_test.go
// Copyright 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. package bytesconv import ( "bytes" cRand "crypto/rand" "math/rand" "strings" "testing" "time" ) var ( testString = "Albert Einstein: Logic will get you from A to B. Imagination will take you everywhere." testBytes = []byte(testString) ) func rawBytesToStr(b []byte) string { return string(b) } func rawStrToBytes(s string) []byte { return []byte(s) } // go test -v func TestBytesToString(t *testing.T) { data := make([]byte, 1024) for i := 0; i < 100; i++ { _, err := cRand.Read(data) if err != nil { t.Fatal(err) } if rawBytesToStr(data) != BytesToString(data) { t.Fatal("don't match") } } } func TestBytesToStringEmpty(t *testing.T) { if got := BytesToString([]byte{}); got != "" { t.Fatalf("BytesToString([]byte{}) = %q; want empty string", got) } if got := BytesToString(nil); got != "" { t.Fatalf("BytesToString(nil) = %q; want empty string", got) } } const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" const ( letterIdxBits = 6 // 6 bits to represent a letter index letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits ) var src = rand.New(rand.NewSource(time.Now().UnixNano())) func RandStringBytesMaskImprSrcSB(n int) string { sb := strings.Builder{} sb.Grow(n) // A src.Int63() generates 63 random bits, enough for letterIdxMax characters! for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; { if remain == 0 { cache, remain = src.Int63(), letterIdxMax } if idx := int(cache & letterIdxMask); idx < len(letterBytes) { sb.WriteByte(letterBytes[idx]) i-- } cache >>= letterIdxBits remain-- } return sb.String() } func TestStringToBytes(t *testing.T) { for i := 0; i < 100; i++ { s := RandStringBytesMaskImprSrcSB(64) if !bytes.Equal(rawStrToBytes(s), StringToBytes(s)) { t.Fatal("don't match") } } } func TestStringToBytesEmpty(t *testing.T) { b := StringToBytes("") if len(b) != 0 { t.Fatalf(`StringToBytes("") length = %d; want 0`, len(b)) } if !bytes.Equal(b, []byte("")) { t.Fatalf(`StringToBytes("") = %v; want []byte("")`, b) } } // go test -v -run=none -bench=^BenchmarkBytesConv -benchmem=true func BenchmarkBytesConvBytesToStrRaw(b *testing.B) { for b.Loop() { rawBytesToStr(testBytes) } } func BenchmarkBytesConvBytesToStr(b *testing.B) { for b.Loop() { BytesToString(testBytes) } } func BenchmarkBytesConvStrToBytesRaw(b *testing.B) { for b.Loop() { rawStrToBytes(testString) } } func BenchmarkBytesConvStrToBytes(b *testing.B) { for b.Loop() { StringToBytes(testString) } }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/internal/bytesconv/bytesconv.go
internal/bytesconv/bytesconv.go
// Copyright 2023 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 bytesconv import ( "unsafe" ) // StringToBytes converts string to byte slice without a memory allocation. // For more details, see https://github.com/golang/go/issues/53003#issuecomment-1140276077. func StringToBytes(s string) []byte { return unsafe.Slice(unsafe.StringData(s), len(s)) } // BytesToString converts byte slice to string without a memory allocation. // For more details, see https://github.com/golang/go/issues/53003#issuecomment-1140276077. func BytesToString(b []byte) string { return unsafe.String(unsafe.SliceData(b), len(b)) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/internal/fs/fs_test.go
internal/fs/fs_test.go
package fs 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 TestFileSystem_Open(t *testing.T) { var testFile *os.File mockFS := &mockFileSystem{ open: func(name string) (http.File, error) { return testFile, nil }, } fs := &FileSystem{mockFS} file, err := fs.Open("foo") require.NoError(t, err) assert.Equal(t, testFile, file) } func TestFileSystem_Open_err(t *testing.T) { testError := errors.New("mock") mockFS := &mockFileSystem{ open: func(_ string) (http.File, error) { return nil, testError }, } fs := &FileSystem{mockFS} file, err := fs.Open("foo") require.ErrorIs(t, err, testError) assert.Nil(t, file) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/internal/fs/fs.go
internal/fs/fs.go
package fs import ( "io/fs" "net/http" ) // FileSystem implements an [fs.FS]. type FileSystem struct { http.FileSystem } // Open passes `Open` to the upstream implementation and return an [fs.File]. func (o FileSystem) Open(name string) (fs.File, error) { f, err := o.FileSystem.Open(name) if err != nil { return nil, err } return fs.File(f), nil }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/render/json.go
render/json.go
// 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 ( "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 } // IndentedJSON contains the given interface object. type IndentedJSON struct { Data any } // SecureJSON contains the given interface object and its prefix. type SecureJSON struct { Prefix string 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 } // PureJSON 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 = []string{"application/json"} ) // Render (JSON) writes data with custom ContentType. func (r JSON) Render(w http.ResponseWriter) error { return WriteJSON(w, r.Data) } // WriteContentType (JSON) writes JSON ContentType. func (r JSON) WriteContentType(w http.ResponseWriter) { writeContentType(w, jsonContentType) } // WriteJSON marshals the given interface object and writes it with custom ContentType. func WriteJSON(w http.ResponseWriter, obj any) error { writeContentType(w, jsonContentType) jsonBytes, err := json.API.Marshal(obj) if err != nil { return err } _, err = w.Write(jsonBytes) return err } // Render (IndentedJSON) marshals the given interface object and writes it with custom ContentType. func (r IndentedJSON) Render(w http.ResponseWriter) error { r.WriteContentType(w) jsonBytes, err := json.API.MarshalIndent(r.Data, "", " ") if err != nil { return err } _, err = w.Write(jsonBytes) return err } // WriteContentType (IndentedJSON) writes JSON ContentType. func (r IndentedJSON) WriteContentType(w http.ResponseWriter) { writeContentType(w, jsonContentType) } // Render (SecureJSON) marshals the given interface object and writes it with custom ContentType. func (r SecureJSON) Render(w http.ResponseWriter) error { r.WriteContentType(w) jsonBytes, err := json.API.Marshal(r.Data) if err != nil { return err } // if the jsonBytes is array values if bytes.HasPrefix(jsonBytes, bytesconv.StringToBytes("[")) && bytes.HasSuffix(jsonBytes, bytesconv.StringToBytes("]")) { if _, err = w.Write(bytesconv.StringToBytes(r.Prefix)); err != nil { return err } } _, err = w.Write(jsonBytes) return err } // WriteContentType (SecureJSON) writes JSON ContentType. func (r SecureJSON) WriteContentType(w http.ResponseWriter) { writeContentType(w, jsonContentType) } // Render (JsonpJSON) marshals the given interface object and writes it and its callback with custom ContentType. func (r JsonpJSON) Render(w http.ResponseWriter) (err error) { r.WriteContentType(w) ret, err := json.API.Marshal(r.Data) if err != nil { return err } if r.Callback == "" { _, err = w.Write(ret) return err } callback := template.JSEscapeString(r.Callback) if _, err = w.Write(bytesconv.StringToBytes(callback)); err != nil { return err } if _, err = w.Write(bytesconv.StringToBytes("(")); err != nil { return err } if _, err = w.Write(ret); err != nil { return err } if _, err = w.Write(bytesconv.StringToBytes(");")); err != nil { return err } return nil } // WriteContentType (JsonpJSON) writes Javascript ContentType. func (r JsonpJSON) WriteContentType(w http.ResponseWriter) { writeContentType(w, jsonpContentType) } // Render (AsciiJSON) marshals the given interface object and writes it with custom ContentType. func (r AsciiJSON) Render(w http.ResponseWriter) error { r.WriteContentType(w) ret, err := json.API.Marshal(r.Data) if err != nil { return err } var buffer bytes.Buffer escapeBuf := make([]byte, 0, 6) // Preallocate 6 bytes for Unicode escape sequences for _, r := range bytesconv.BytesToString(ret) { if r > unicode.MaxASCII { escapeBuf = fmt.Appendf(escapeBuf[:0], "\\u%04x", r) // Reuse escapeBuf buffer.Write(escapeBuf) } else { buffer.WriteByte(byte(r)) } } _, err = w.Write(buffer.Bytes()) return err } // WriteContentType (AsciiJSON) writes JSON ContentType. func (r AsciiJSON) WriteContentType(w http.ResponseWriter) { writeContentType(w, jsonASCIIContentType) } // Render (PureJSON) writes custom ContentType and encodes the given interface object. func (r PureJSON) Render(w http.ResponseWriter) error { r.WriteContentType(w) encoder := json.API.NewEncoder(w) encoder.SetEscapeHTML(false) return encoder.Encode(r.Data) } // WriteContentType (PureJSON) writes custom ContentType. func (r PureJSON) WriteContentType(w http.ResponseWriter) { writeContentType(w, jsonContentType) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/render/text.go
render/text.go
// 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 format. type String struct { Format string Data []any } var plainContentType = []string{"text/plain; charset=utf-8"} // Render (String) writes data with custom ContentType. func (r String) 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, plainContentType) } // 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, format, data...) return } _, err = w.Write(bytesconv.StringToBytes(format)) return }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/render/data.go
render/data.go
// 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" // Data contains ContentType and bytes data. type Data struct { ContentType string Data []byte } // Render (Data) writes data with custom ContentType. func (r Data) Render(w http.ResponseWriter) (err error) { r.WriteContentType(w) _, err = w.Write(r.Data) return } // WriteContentType (Data) writes custom ContentType. func (r Data) WriteContentType(w http.ResponseWriter) { writeContentType(w, []string{r.ContentType}) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/render/render_test.go
render/render_test.go
// 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 ( "encoding/xml" "errors" "html/template" "net" "net/http" "net/http/httptest" "strconv" "strings" "testing" "github.com/gin-gonic/gin/codec/json" testdata "github.com/gin-gonic/gin/testdata/protoexample" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" ) // TODO unit tests // test errors func TestRenderJSON(t *testing.T) { w := httptest.NewRecorder() data := map[string]any{ "foo": "bar", "html": "<b>", } (JSON{data}).WriteContentType(w) assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type")) err := (JSON{data}).Render(w) require.NoError(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 require.Error(t, (JSON{data}).Render(w)) } func TestRenderIndentedJSON(t *testing.T) { w := httptest.NewRecorder() data := map[string]any{ "foo": "bar", "bar": "foo", } err := (IndentedJSON{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 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 := httptest.NewRecorder() data := map[string]any{ "foo": "bar", } (SecureJSON{"while(1);", data}).WriteContentType(w1) assert.Equal(t, "application/json; charset=utf-8", w1.Header().Get("Content-Type")) err1 := (SecureJSON{"while(1);", data}).Render(w1) require.NoError(t, err1) assert.JSONEq(t, "{\"foo\":\"bar\"}", w1.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w1.Header().Get("Content-Type")) w2 := httptest.NewRecorder() datas := []map[string]any{{ "foo": "bar", }, { "bar": "foo", }} err2 := (SecureJSON{"while(1);", datas}).Render(w2) require.NoError(t, err2) assert.Equal(t, "while(1);[{\"foo\":\"bar\"},{\"bar\":\"foo\"}]", w2.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w2.Header().Get("Content-Type")) } func TestRenderSecureJSONFail(t *testing.T) { w := httptest.NewRecorder() data := make(chan int) // json: unsupported type: chan int err := (SecureJSON{"while(1);", data}).Render(w) require.Error(t, err) } func TestRenderJsonpJSON(t *testing.T) { w1 := httptest.NewRecorder() data := map[string]any{ "foo": "bar", } (JsonpJSON{"x", data}).WriteContentType(w1) assert.Equal(t, "application/javascript; charset=utf-8", w1.Header().Get("Content-Type")) err1 := (JsonpJSON{"x", data}).Render(w1) require.NoError(t, err1) assert.Equal(t, "x({\"foo\":\"bar\"});", w1.Body.String()) assert.Equal(t, "application/javascript; charset=utf-8", w1.Header().Get("Content-Type")) w2 := httptest.NewRecorder() datas := []map[string]any{{ "foo": "bar", }, { "bar": "foo", }} err2 := (JsonpJSON{"x", datas}).Render(w2) require.NoError(t, err2) assert.Equal(t, "x([{\"foo\":\"bar\"},{\"bar\":\"foo\"}]);", w2.Body.String()) assert.Equal(t, "application/javascript; charset=utf-8", w2.Header().Get("Content-Type")) } type errorWriter struct { bufString string *httptest.ResponseRecorder } var _ http.ResponseWriter = (*errorWriter)(nil) func (w *errorWriter) Write(buf []byte) (int, error) { if string(buf) == w.bufString { return 0, errors.New(`write "` + w.bufString + `" error`) } return w.ResponseRecorder.Write(buf) } func TestRenderJsonpJSONError(t *testing.T) { ew := &errorWriter{ ResponseRecorder: httptest.NewRecorder(), } jsonpJSON := JsonpJSON{ Callback: "foo", Data: map[string]string{ "foo": "bar", }, } cb := template.JSEscapeString(jsonpJSON.Callback) ew.bufString = cb err := jsonpJSON.Render(ew) // error was returned while writing callback assert.Equal(t, `write "`+cb+`" error`, err.Error()) ew.bufString = `(` err = jsonpJSON.Render(ew) assert.Equal(t, `write "`+`(`+`" error`, err.Error()) data, _ := json.API.Marshal(jsonpJSON.Data) // error was returned while writing data ew.bufString = string(data) err = jsonpJSON.Render(ew) assert.Equal(t, `write "`+string(data)+`" error`, err.Error()) ew.bufString = `);` err = jsonpJSON.Render(ew) assert.Equal(t, `write "`+`);`+`" error`, err.Error()) } func TestRenderJsonpJSONError2(t *testing.T) { w := httptest.NewRecorder() data := map[string]any{ "foo": "bar", } (JsonpJSON{"", data}).WriteContentType(w) assert.Equal(t, "application/javascript; charset=utf-8", w.Header().Get("Content-Type")) e := (JsonpJSON{"", data}).Render(w) require.NoError(t, e) assert.JSONEq(t, "{\"foo\":\"bar\"}", w.Body.String()) assert.Equal(t, "application/javascript; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderJsonpJSONFail(t *testing.T) { w := httptest.NewRecorder() data := make(chan int) // json: unsupported type: chan int err := (JsonpJSON{"x", data}).Render(w) require.Error(t, err) } func TestRenderAsciiJSON(t *testing.T) { w1 := httptest.NewRecorder() data1 := map[string]any{ "lang": "GO语言", "tag": "<br>", } err := (AsciiJSON{data1}).Render(w1) require.NoError(t, err) assert.JSONEq(t, "{\"lang\":\"GO\\u8bed\\u8a00\",\"tag\":\"\\u003cbr\\u003e\"}", w1.Body.String()) assert.Equal(t, "application/json", w1.Header().Get("Content-Type")) w2 := httptest.NewRecorder() data2 := 3.1415926 err = (AsciiJSON{data2}).Render(w2) require.NoError(t, err) assert.Equal(t, "3.1415926", w2.Body.String()) } func TestRenderAsciiJSONFail(t *testing.T) { w := httptest.NewRecorder() data := make(chan int) // json: unsupported type: chan int require.Error(t, (AsciiJSON{data}).Render(w)) } func TestRenderPureJSON(t *testing.T) { w := httptest.NewRecorder() data := map[string]any{ "foo": "bar", "html": "<b>", } err := (PureJSON{data}).Render(w) require.NoError(t, err) assert.JSONEq(t, "{\"foo\":\"bar\",\"html\":\"<b>\"}\n", w.Body.String()) assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type")) } type xmlmap map[string]any // Allows type H to be used with xml.Marshal func (h xmlmap) MarshalXML(e *xml.Encoder, start xml.StartElement) error { start.Name = xml.Name{ Space: "", Local: "map", } if err := e.EncodeToken(start); err != nil { return err } for key, value := range h { elem := xml.StartElement{ Name: xml.Name{Space: "", Local: key}, Attr: []xml.Attr{}, } if err := e.EncodeElement(value, elem); err != nil { return err } } return e.EncodeToken(xml.EndElement{Name: start.Name}) } func TestRenderYAML(t *testing.T) { w := httptest.NewRecorder() data := ` a : Easy! b: c: 2 d: [3, 4] ` (YAML{data}).WriteContentType(w) assert.Equal(t, "application/yaml; charset=utf-8", w.Header().Get("Content-Type")) err := (YAML{data}).Render(w) require.NoError(t, err) // With github.com/goccy/go-yaml, the output format is different from gopkg.in/yaml.v3 // We're checking that the output contains the expected data, not the exact formatting output := w.Body.String() assert.Contains(t, output, "a : Easy!") assert.Contains(t, output, "b:") assert.Contains(t, output, "c: 2") assert.Contains(t, output, "d: [3, 4]") assert.Equal(t, "application/yaml; charset=utf-8", w.Header().Get("Content-Type")) } type fail struct{} // Hook MarshalYAML func (ft *fail) MarshalYAML() (any, error) { return nil, errors.New("fail") } func TestRenderYAMLFail(t *testing.T) { w := httptest.NewRecorder() err := (YAML{&fail{}}).Render(w) require.Error(t, err) } func TestRenderTOML(t *testing.T) { w := httptest.NewRecorder() data := map[string]any{ "foo": "bar", "html": "<b>", } (TOML{data}).WriteContentType(w) assert.Equal(t, "application/toml; charset=utf-8", w.Header().Get("Content-Type")) err := (TOML{data}).Render(w) require.NoError(t, err) assert.Equal(t, "foo = 'bar'\nhtml = '<b>'\n", w.Body.String()) assert.Equal(t, "application/toml; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderTOMLFail(t *testing.T) { w := httptest.NewRecorder() err := (TOML{net.IPv4bcast}).Render(w) require.Error(t, err) } // test Protobuf rendering func TestRenderProtoBuf(t *testing.T) { w := httptest.NewRecorder() reps := []int64{int64(1), int64(2)} label := "test" data := &testdata.Test{ Label: &label, Reps: reps, } (ProtoBuf{data}).WriteContentType(w) protoData, err := proto.Marshal(data) require.NoError(t, err) assert.Equal(t, "application/x-protobuf", w.Header().Get("Content-Type")) err = (ProtoBuf{data}).Render(w) require.NoError(t, err) assert.Equal(t, string(protoData), w.Body.String()) assert.Equal(t, "application/x-protobuf", w.Header().Get("Content-Type")) } func TestRenderProtoBufFail(t *testing.T) { w := httptest.NewRecorder() data := &testdata.Test{} err := (ProtoBuf{data}).Render(w) require.Error(t, err) } func TestRenderXML(t *testing.T) { w := httptest.NewRecorder() data := xmlmap{ "foo": "bar", } (XML{data}).WriteContentType(w) assert.Equal(t, "application/xml; charset=utf-8", w.Header().Get("Content-Type")) err := (XML{data}).Render(w) require.NoError(t, err) assert.Equal(t, "<map><foo>bar</foo></map>", w.Body.String()) assert.Equal(t, "application/xml; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderRedirect(t *testing.T) { req, err := http.NewRequest(http.MethodGet, "/test-redirect", nil) require.NoError(t, err) data1 := Redirect{ Code: http.StatusMovedPermanently, Request: req, Location: "/new/location", } w := httptest.NewRecorder() err = data1.Render(w) require.NoError(t, err) data2 := Redirect{ Code: http.StatusOK, Request: req, Location: "/new/location", } w = httptest.NewRecorder() assert.PanicsWithValue(t, "Cannot redirect with status code 200", func() { err := data2.Render(w) require.NoError(t, err) }) data3 := Redirect{ Code: http.StatusCreated, Request: req, Location: "/new/location", } w = httptest.NewRecorder() err = data3.Render(w) require.NoError(t, err) // only improve coverage data2.WriteContentType(w) } func TestRenderData(t *testing.T) { w := httptest.NewRecorder() data := []byte("#!PNG some raw data") err := (Data{ ContentType: "image/png", Data: data, }).Render(w) require.NoError(t, err) assert.Equal(t, "#!PNG some raw data", w.Body.String()) assert.Equal(t, "image/png", w.Header().Get("Content-Type")) } func TestRenderString(t *testing.T) { w := httptest.NewRecorder() (String{ Format: "hello %s %d", Data: []any{}, }).WriteContentType(w) assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) err := (String{ Format: "hola %s %d", Data: []any{"manu", 2}, }).Render(w) require.NoError(t, err) assert.Equal(t, "hola manu 2", w.Body.String()) assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderStringLenZero(t *testing.T) { w := httptest.NewRecorder() err := (String{ Format: "hola %s %d", Data: []any{}, }).Render(w) require.NoError(t, err) assert.Equal(t, "hola %s %d", w.Body.String()) assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderHTMLTemplate(t *testing.T) { w := httptest.NewRecorder() templ := template.Must(template.New("t").Parse(`Hello {{.name}}`)) htmlRender := HTMLProduction{Template: templ} instance := htmlRender.Instance("t", map[string]any{ "name": "alexandernyquist", }) err := instance.Render(w) require.NoError(t, err) assert.Equal(t, "Hello alexandernyquist", w.Body.String()) assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderHTMLTemplateEmptyName(t *testing.T) { w := httptest.NewRecorder() templ := template.Must(template.New("").Parse(`Hello {{.name}}`)) htmlRender := HTMLProduction{Template: templ} instance := htmlRender.Instance("", map[string]any{ "name": "alexandernyquist", }) err := instance.Render(w) require.NoError(t, err) assert.Equal(t, "Hello alexandernyquist", w.Body.String()) assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderHTMLDebugFiles(t *testing.T) { w := httptest.NewRecorder() htmlRender := HTMLDebug{ Files: []string{"../testdata/template/hello.tmpl"}, Glob: "", FileSystem: nil, Patterns: nil, Delims: Delims{Left: "{[{", Right: "}]}"}, FuncMap: nil, } instance := htmlRender.Instance("hello.tmpl", map[string]any{ "name": "thinkerou", }) err := instance.Render(w) require.NoError(t, err) assert.Equal(t, "<h1>Hello thinkerou</h1>", w.Body.String()) assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderHTMLDebugGlob(t *testing.T) { w := httptest.NewRecorder() htmlRender := HTMLDebug{ Files: nil, Glob: "../testdata/template/hello*", FileSystem: nil, Patterns: nil, Delims: Delims{Left: "{[{", Right: "}]}"}, FuncMap: nil, } instance := htmlRender.Instance("hello.tmpl", map[string]any{ "name": "thinkerou", }) err := instance.Render(w) require.NoError(t, err) assert.Equal(t, "<h1>Hello thinkerou</h1>", w.Body.String()) assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderHTMLDebugFS(t *testing.T) { w := httptest.NewRecorder() htmlRender := HTMLDebug{ Files: nil, Glob: "", FileSystem: http.Dir("../testdata/template"), Patterns: []string{"hello.tmpl"}, Delims: Delims{Left: "{[{", Right: "}]}"}, FuncMap: nil, } instance := htmlRender.Instance("hello.tmpl", map[string]any{ "name": "thinkerou", }) err := instance.Render(w) require.NoError(t, err) assert.Equal(t, "<h1>Hello thinkerou</h1>", w.Body.String()) assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } func TestRenderHTMLDebugPanics(t *testing.T) { htmlRender := HTMLDebug{ Files: nil, Glob: "", FileSystem: nil, Patterns: nil, Delims: Delims{"{{", "}}"}, FuncMap: nil, } assert.Panics(t, func() { htmlRender.Instance("", nil) }) } func TestRenderReader(t *testing.T) { w := httptest.NewRecorder() body := "#!PNG some raw data" headers := make(map[string]string) headers["Content-Disposition"] = `attachment; filename="filename.png"` headers["x-request-id"] = "requestId" err := (Reader{ ContentLength: int64(len(body)), ContentType: "image/png", Reader: strings.NewReader(body), Headers: headers, }).Render(w) require.NoError(t, err) assert.Equal(t, body, w.Body.String()) assert.Equal(t, "image/png", w.Header().Get("Content-Type")) assert.Equal(t, strconv.Itoa(len(body)), w.Header().Get("Content-Length")) assert.Equal(t, headers["Content-Disposition"], w.Header().Get("Content-Disposition")) assert.Equal(t, headers["x-request-id"], w.Header().Get("x-request-id")) } func TestRenderReaderNoContentLength(t *testing.T) { w := httptest.NewRecorder() body := "#!PNG some raw data" headers := make(map[string]string) headers["Content-Disposition"] = `attachment; filename="filename.png"` headers["x-request-id"] = "requestId" err := (Reader{ ContentLength: -1, ContentType: "image/png", Reader: strings.NewReader(body), Headers: headers, }).Render(w) require.NoError(t, err) assert.Equal(t, body, w.Body.String()) assert.Equal(t, "image/png", w.Header().Get("Content-Type")) assert.NotContains(t, "Content-Length", w.Header()) assert.Equal(t, headers["Content-Disposition"], w.Header().Get("Content-Disposition")) assert.Equal(t, headers["x-request-id"], w.Header().Get("x-request-id")) } func TestRenderWriteError(t *testing.T) { data := []any{"value1", "value2"} prefix := "my-prefix:" r := SecureJSON{Data: data, Prefix: prefix} ew := &errorWriter{ bufString: prefix, ResponseRecorder: httptest.NewRecorder(), } err := r.Render(ew) require.Error(t, err) assert.Equal(t, `write "my-prefix:" error`, err.Error()) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/render/xml.go
render/xml.go
// 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 ( "encoding/xml" "net/http" ) // XML contains the given interface object. type XML struct { Data any } var xmlContentType = []string{"application/xml; charset=utf-8"} // Render (XML) encodes the given interface object and writes data with custom ContentType. func (r XML) Render(w http.ResponseWriter) error { r.WriteContentType(w) return xml.NewEncoder(w).Encode(r.Data) } // WriteContentType (XML) writes XML ContentType for response. func (r XML) WriteContentType(w http.ResponseWriter) { writeContentType(w, xmlContentType) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/render/msgpack.go
render/msgpack.go
// Copyright 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 nomsgpack. // See: https://github.com/gin-gonic/gin/pull/1852/ var ( _ Render = MsgPack{} ) // MsgPack contains the given interface object. type MsgPack struct { Data any } var msgpackContentType = []string{"application/msgpack; charset=utf-8"} // WriteContentType (MsgPack) writes MsgPack ContentType. func (r MsgPack) WriteContentType(w http.ResponseWriter) { writeContentType(w, msgpackContentType) } // Render (MsgPack) 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. func WriteMsgPack(w http.ResponseWriter, obj any) error { writeContentType(w, msgpackContentType) var mh codec.MsgpackHandle return codec.NewEncoder(w, &mh).Encode(obj) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/render/render.go
render/render.go
// 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" // Render interface is to be implemented by JSON, XML, HTML, YAML and so on. type Render interface { // Render writes data with custom ContentType. Render(http.ResponseWriter) error // WriteContentType writes custom ContentType. WriteContentType(w http.ResponseWriter) } var ( _ Render = (*JSON)(nil) _ Render = (*IndentedJSON)(nil) _ Render = (*SecureJSON)(nil) _ Render = (*JsonpJSON)(nil) _ Render = (*XML)(nil) _ Render = (*String)(nil) _ Render = (*Redirect)(nil) _ Render = (*Data)(nil) _ Render = (*HTML)(nil) _ HTMLRender = (*HTMLDebug)(nil) _ HTMLRender = (*HTMLProduction)(nil) _ Render = (*YAML)(nil) _ Render = (*Reader)(nil) _ Render = (*AsciiJSON)(nil) _ Render = (*ProtoBuf)(nil) _ Render = (*TOML)(nil) ) func writeContentType(w http.ResponseWriter, value []string) { header := w.Header() if val := header["Content-Type"]; len(val) == 0 { header["Content-Type"] = value } }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/render/reader.go
render/reader.go
// Copyright 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 { ContentType string ContentLength int64 Reader io.Reader Headers map[string]string } // Render (Reader) writes data with custom ContentType and headers. func (r Reader) Render(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) } 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 from r.Headers into response. func (r Reader) writeHeaders(w http.ResponseWriter) { header := w.Header() for k, v := range r.Headers { if header.Get(k) == "" { header.Set(k, v) } } }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/render/yaml.go
render/yaml.go
// 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 yamlContentType = []string{"application/yaml; charset=utf-8"} // Render (YAML) marshals the given interface object and writes data with custom ContentType. func (r YAML) Render(w http.ResponseWriter) error { r.WriteContentType(w) bytes, err := 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) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/render/reader_test.go
render/reader_test.go
// 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. package render import ( "net/http/httptest" "strings" "testing" "github.com/stretchr/testify/require" ) func TestReaderRenderNoHeaders(t *testing.T) { content := "test" r := Reader{ ContentLength: int64(len(content)), Reader: strings.NewReader(content), } err := r.Render(httptest.NewRecorder()) require.NoError(t, err) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/render/protobuf.go
render/protobuf.go
// Copyright 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 ( "net/http" "google.golang.org/protobuf/proto" ) // ProtoBuf contains the given interface object. type ProtoBuf struct { Data any } var protobufContentType = []string{"application/x-protobuf"} // Render (ProtoBuf) marshals the given interface object and writes data with custom ContentType. func (r ProtoBuf) Render(w http.ResponseWriter) error { r.WriteContentType(w) bytes, err := proto.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, protobufContentType) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/render/html.go
render/html.go
// 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 ( "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 { // Left delimiter, defaults to {{. Left string // Right delimiter, defaults to }}. Right string } // HTMLRender interface is to be implemented by HTMLProduction and HTMLDebug. type HTMLRender 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 } // 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 contains template reference and its name with given interface object. type HTML struct { Template *template.Template Name string Data any } var htmlContentType = []string{"text/html; charset=utf-8"} // Instance (HTMLProduction) returns an HTML instance which it realizes Render interface. func (r HTMLProduction) Instance(name string, data any) Render { return HTML{ Template: r.Template, Name: name, Data: data, } } // Instance (HTMLDebug) returns an HTML instance which it realizes Render interface. func (r HTMLDebug) Instance(name string, data any) Render { return HTML{ Template: r.loadTemplate(), Name: name, Data: data, } } func (r HTMLDebug) loadTemplate() *template.Template { if r.FuncMap == nil { r.FuncMap = template.FuncMap{} } if len(r.Files) > 0 { return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseFiles(r.Files...)) } if r.Glob != "" { return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseGlob(r.Glob)) } if r.FileSystem != nil && len(r.Patterns) > 0 { return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseFS( fs.FileSystem{FileSystem: r.FileSystem}, r.Patterns...)) } panic("the HTML debug render was created without files or glob pattern or file system with patterns") } // Render (HTML) executes template and writes its result with custom ContentType for response. func (r HTML) Render(w http.ResponseWriter) error { r.WriteContentType(w) if r.Name == "" { return r.Template.Execute(w, r.Data) } return r.Template.ExecuteTemplate(w, r.Name, r.Data) } // WriteContentType (HTML) writes HTML ContentType. func (r HTML) WriteContentType(w http.ResponseWriter) { writeContentType(w, htmlContentType) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/render/redirect.go
render/redirect.go
// 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" ) // Redirect contains the http request reference and redirects status code and location. type Redirect struct { Code int Request *http.Request Location string } // Render (Redirect) redirects the http request to new location and writes redirect response. func (r Redirect) Render(w http.ResponseWriter) error { if (r.Code < http.StatusMultipleChoices || r.Code > http.StatusPermanentRedirect) && 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 Redirect) WriteContentType(http.ResponseWriter) {}
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/render/toml.go
render/toml.go
// 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 tomlContentType = []string{"application/toml; charset=utf-8"} // Render (TOML) marshals the given interface object and writes data with custom ContentType. func (r TOML) Render(w http.ResponseWriter) error { r.WriteContentType(w) bytes, err := 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) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/render/render_msgpack_test.go
render/render_msgpack_test.go
// 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. //go:build !nomsgpack package render import ( "bytes" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/ugorji/go/codec" ) // TODO unit tests // test errors func TestRenderMsgPack(t *testing.T) { w := httptest.NewRecorder() data := map[string]any{ "foo": "bar", } (MsgPack{data}).WriteContentType(w) assert.Equal(t, "application/msgpack; charset=utf-8", w.Header().Get("Content-Type")) err := (MsgPack{data}).Render(w) require.NoError(t, err) h := new(codec.MsgpackHandle) assert.NotNil(t, h) buf := bytes.NewBuffer([]byte{}) assert.NotNil(t, buf) err = codec.NewEncoder(buf, h).Encode(data) require.NoError(t, err) assert.Equal(t, w.Body.String(), buf.String()) assert.Equal(t, "application/msgpack; charset=utf-8", w.Header().Get("Content-Type")) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/testdata/protoexample/test.pb.go
testdata/protoexample/test.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.27.0 // protoc v3.15.8 // source: test.proto package protoexample import ( protoreflect "google.golang.org/protobuf/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. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type FOO int32 const ( FOO_X FOO = 17 ) // Enum value maps for FOO. var ( FOO_name = map[int32]string{ 17: "X", } FOO_value = map[string]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() protoreflect.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) } // Deprecated: Do not use. func (x *FOO) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FOO(num) return nil } // Deprecated: Use FOO.Descriptor instead. func (FOO) EnumDescriptor() ([]byte, []int) { return file_test_proto_rawDescGZIP(), []int{0} } type Test struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup,json=optionalgroup" json:"optionalgroup,omitempty"` } // Default values for Test fields. const ( Default_Test_Type = int32(77) ) func (x *Test) Reset() { *x = Test{} if protoimpl.UnsafeEnabled { mi := &file_test_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Test) String() string { return protoimpl.X.MessageStringOf(x) } func (*Test) ProtoMessage() {} func (x *Test) ProtoReflect() protoreflect.Message { mi := &file_test_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Test.ProtoReflect.Descriptor instead. func (*Test) Descriptor() ([]byte, []int) { return file_test_proto_rawDescGZIP(), []int{0} } func (x *Test) GetLabel() string { if x != nil && x.Label != nil { return *x.Label } return "" } func (x *Test) GetType() int32 { if x != nil && x.Type != nil { return *x.Type } return Default_Test_Type } func (x *Test) GetReps() []int64 { if x != nil { return x.Reps } return nil } func (x *Test) GetOptionalgroup() *Test_OptionalGroup { if x != nil { return x.Optionalgroup } return nil } type Test_OptionalGroup struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields RequiredField *string `protobuf:"bytes,5,req,name=RequiredField" json:"RequiredField,omitempty"` } func (x *Test_OptionalGroup) Reset() { *x = Test_OptionalGroup{} if protoimpl.UnsafeEnabled { mi := &file_test_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Test_OptionalGroup) String() string { return protoimpl.X.MessageStringOf(x) } func (*Test_OptionalGroup) ProtoMessage() {} func (x *Test_OptionalGroup) ProtoReflect() protoreflect.Message { mi := &file_test_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Test_OptionalGroup.ProtoReflect.Descriptor instead. func (*Test_OptionalGroup) Descriptor() ([]byte, []int) { return file_test_proto_rawDescGZIP(), []int{0, 0} } func (x *Test_OptionalGroup) GetRequiredField() string { if x != nil && x.RequiredField != nil { return *x.RequiredField } return "" } var File_test_proto protoreflect.FileDescriptor var file_test_proto_rawDesc = []byte{ 0x0a, 0x0a, 0x74, 0x65, 0x73, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0c, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x22, 0xc7, 0x01, 0x0a, 0x04, 0x54, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x18, 0x01, 0x20, 0x02, 0x28, 0x09, 0x52, 0x05, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x12, 0x16, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x3a, 0x02, 0x37, 0x37, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x72, 0x65, 0x70, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x03, 0x52, 0x04, 0x72, 0x65, 0x70, 0x73, 0x12, 0x46, 0x0a, 0x0d, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0a, 0x32, 0x20, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x2e, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, 0x0d, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x1a, 0x35, 0x0a, 0x0d, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x12, 0x24, 0x0a, 0x0d, 0x52, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x18, 0x05, 0x20, 0x02, 0x28, 0x09, 0x52, 0x0d, 0x52, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x2a, 0x0c, 0x0a, 0x03, 0x46, 0x4f, 0x4f, 0x12, 0x05, 0x0a, 0x01, 0x58, 0x10, 0x11, } var ( file_test_proto_rawDescOnce sync.Once file_test_proto_rawDescData = file_test_proto_rawDesc ) func file_test_proto_rawDescGZIP() []byte { file_test_proto_rawDescOnce.Do(func() { file_test_proto_rawDescData = protoimpl.X.CompressGZIP(file_test_proto_rawDescData) }) return file_test_proto_rawDescData } var file_test_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_test_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_test_proto_goTypes = []any{ (FOO)(0), // 0: protoexample.FOO (*Test)(nil), // 1: protoexample.Test (*Test_OptionalGroup)(nil), // 2: protoexample.Test.OptionalGroup } var file_test_proto_depIdxs = []int32{ 2, // 0: protoexample.Test.optionalgroup:type_name -> protoexample.Test.OptionalGroup 1, // [1:1] is the sub-list for method output_type 1, // [1:1] is the sub-list for method input_type 1, // [1:1] is the sub-list for extension type_name 1, // [1:1] is the sub-list for extension extendee 0, // [0:1] is the sub-list for field type_name } func init() { file_test_proto_init() } func file_test_proto_init() { if File_test_proto != nil { return } if !protoimpl.UnsafeEnabled { file_test_proto_msgTypes[0].Exporter = func(v any, i int) any { switch v := v.(*Test); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_test_proto_msgTypes[1].Exporter = func(v any, i int) any { switch v := v.(*Test_OptionalGroup); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_test_proto_rawDesc, NumEnums: 1, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_test_proto_goTypes, DependencyIndexes: file_test_proto_depIdxs, EnumInfos: file_test_proto_enumTypes, MessageInfos: file_test_proto_msgTypes, }.Build() File_test_proto = out.File file_test_proto_rawDesc = nil file_test_proto_goTypes = nil file_test_proto_depIdxs = nil }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/binding/json.go
binding/json.go
// 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 binding import ( "bytes" "errors" "io" "net/http" "github.com/gin-gonic/gin/codec/json" ) // EnableDecoderUseNumber is used to call the UseNumber method on the JSON // Decoder instance. UseNumber causes the Decoder to unmarshal a number into an // any as a Number instead of as a float64. var EnableDecoderUseNumber = false // EnableDecoderDisallowUnknownFields 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 which 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 { if req == nil || req.Body == nil { return errors.New("invalid request") } return decodeJSON(req.Body, obj) } func (jsonBinding) BindBody(body []byte, obj any) error { return decodeJSON(bytes.NewReader(body), obj) } func decodeJSON(r io.Reader, obj any) error { decoder := json.API.NewDecoder(r) if EnableDecoderUseNumber { decoder.UseNumber() } if EnableDecoderDisallowUnknownFields { decoder.DisallowUnknownFields() } if err := decoder.Decode(obj); err != nil { return err } return validate(obj) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/binding/form.go
binding/form.go
// 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 binding import ( "errors" "net/http" ) const defaultMemory = 32 << 20 type ( formBinding struct{} formPostBinding struct{} formMultipartBinding struct{} ) func (formBinding) Name() string { return "form" } func (formBinding) Bind(req *http.Request, obj any) error { if err := req.ParseForm(); err != nil { return err } 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) 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) } func (formMultipartBinding) Name() string { return "multipart/form-data" } func (formMultipartBinding) Bind(req *http.Request, obj any) error { if err := req.ParseMultipartForm(defaultMemory); err != nil { return err } if err := mappingByPtr(obj, (*multipartRequest)(req), "form"); err != nil { return err } return validate(obj) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/binding/xml_test.go
binding/xml_test.go
// 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. package binding import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestXMLBindingBindBody(t *testing.T) { var s struct { Foo string `xml:"foo"` } xmlBody := `<?xml version="1.0" encoding="UTF-8"?> <root> <foo>FOO</foo> </root>` err := xmlBinding{}.BindBody([]byte(xmlBody), &s) require.NoError(t, err) assert.Equal(t, "FOO", s.Foo) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false
gin-gonic/gin
https://github.com/gin-gonic/gin/blob/9914178584e42458ff7d23891463a880f58c9d86/binding/xml.go
binding/xml.go
// 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 binding import ( "bytes" "encoding/xml" "io" "net/http" ) type xmlBinding struct{} func (xmlBinding) Name() string { return "xml" } func (xmlBinding) Bind(req *http.Request, obj any) error { return decodeXML(req.Body, obj) } func (xmlBinding) BindBody(body []byte, obj any) error { return decodeXML(bytes.NewReader(body), obj) } func decodeXML(r io.Reader, obj any) error { decoder := xml.NewDecoder(r) if err := decoder.Decode(obj); err != nil { return err } return validate(obj) }
go
MIT
9914178584e42458ff7d23891463a880f58c9d86
2026-01-07T08:35:43.439653Z
false