context_test.go
This file
Path
context_test.go
4,057 lines · 117.7 KiB · Go
Last changed by
fix(context): load Keys under the mutex in Copy (#4854)HazyLabbefore adoption1bd0ecf
History of this fileTake it
1// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package gin67import (8 "bytes"9 "context"10 "crypto/tls"11 "errors"12 "fmt"13 "html/template"14 "io"15 "io/fs"16 "mime/multipart"17 "net"18 "net/http"19 "net/http/httptest"20 "net/url"21 "os"22 "path/filepath"23 "reflect"24 "strconv"25 "strings"26 "sync"27 "testing"28 "time"2930 "github.com/gin-contrib/sse"31 "github.com/gin-gonic/gin/binding"32 "github.com/gin-gonic/gin/codec/json"33 testdata "github.com/gin-gonic/gin/testdata/protoexample"34 "github.com/stretchr/testify/assert"35 "github.com/stretchr/testify/require"36 "go.mongodb.org/mongo-driver/v2/bson"37 "google.golang.org/protobuf/proto"38)3940var _ context.Context = (*Context)(nil)4142var errTestRender = errors.New("TestRender")4344// Unit tests TODO45// func (c *Context) File(filepath string) {46// func (c *Context) Negotiate(code int, config Negotiate) {47// BAD case: func (c *Context) Render(code int, render render.Render, obj ...any) {48// test that information is not leaked when reusing Contexts (using the Pool)4950func createMultipartRequest() *http.Request {51 boundary := "--testboundary"52 body := new(bytes.Buffer)53 mw := multipart.NewWriter(body)54 defer mw.Close()5556 must(mw.SetBoundary(boundary))57 must(mw.WriteField("foo", "bar"))58 must(mw.WriteField("bar", "10"))59 must(mw.WriteField("bar", "foo2"))60 must(mw.WriteField("array", "first"))61 must(mw.WriteField("array", "second"))62 must(mw.WriteField("id", ""))63 must(mw.WriteField("time_local", "31/12/2016 14:55"))64 must(mw.WriteField("time_utc", "31/12/2016 14:55"))65 must(mw.WriteField("time_location", "31/12/2016 14:55"))66 must(mw.WriteField("names[a]", "thinkerou"))67 must(mw.WriteField("names[b]", "tianou"))68 req, err := http.NewRequest(http.MethodPost, "/", body)69 must(err)70 req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)71 return req72}7374func must(err error) {75 if err != nil {76 panic(err.Error())77 }78}7980// TestContextFile tests the Context.File() method81func TestContextFile(t *testing.T) {82 // Test serving an existing file83 t.Run("serve existing file", func(t *testing.T) {84 // Create a temporary test file85 testFile := "testdata/test_file.txt"8687 w := httptest.NewRecorder()88 c, _ := CreateTestContext(w)89 c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)9091 c.File(testFile)9293 assert.Equal(t, http.StatusOK, w.Code)94 assert.Contains(t, w.Body.String(), "This is a test file")95 assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type"))96 })9798 // Test serving a non-existent file99 t.Run("serve non-existent file", func(t *testing.T) {100 w := httptest.NewRecorder()101 c, _ := CreateTestContext(w)102 c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)103104 c.File("non_existent_file.txt")105106 assert.Equal(t, http.StatusNotFound, w.Code)107 })108109 // Test serving a directory (should return 200 with directory listing or 403 Forbidden)110 t.Run("serve directory", func(t *testing.T) {111 w := httptest.NewRecorder()112 c, _ := CreateTestContext(w)113 c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)114115 c.File(".")116117 // Directory serving can return either 200 (with listing) or 403 (forbidden)118 assert.True(t, w.Code == http.StatusOK || w.Code == http.StatusForbidden)119 })120121 // Test with HEAD request122 t.Run("HEAD request", func(t *testing.T) {123 testFile := "testdata/test_file.txt"124125 w := httptest.NewRecorder()126 c, _ := CreateTestContext(w)127 c.Request = httptest.NewRequest(http.MethodHead, "/test", nil)128129 c.File(testFile)130131 assert.Equal(t, http.StatusOK, w.Code)132 assert.Empty(t, w.Body.String()) // HEAD request should not return body133 assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type"))134 })135136 // Test with Range request137 t.Run("Range request", func(t *testing.T) {138 testFile := "testdata/test_file.txt"139140 w := httptest.NewRecorder()141 c, _ := CreateTestContext(w)142 c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)143 c.Request.Header.Set("Range", "bytes=0-10")144145 c.File(testFile)146147 assert.Equal(t, http.StatusPartialContent, w.Code)148 assert.Equal(t, "bytes", w.Header().Get("Accept-Ranges"))149 assert.Contains(t, w.Header().Get("Content-Range"), "bytes 0-10")150 })151}152153func TestContextFormFile(t *testing.T) {154 buf := new(bytes.Buffer)155 mw := multipart.NewWriter(buf)156 w, err := mw.CreateFormFile("file", "test")157 require.NoError(t, err)158 _, err = w.Write([]byte("test"))159 require.NoError(t, err)160 mw.Close()161 c, _ := CreateTestContext(httptest.NewRecorder())162 c.Request, _ = http.NewRequest(http.MethodPost, "/", buf)163 c.Request.Header.Set("Content-Type", mw.FormDataContentType())164 f, err := c.FormFile("file")165 require.NoError(t, err)166 assert.Equal(t, "test", f.Filename)167168 require.NoError(t, c.SaveUploadedFile(f, "test"))169}170171func TestContextFormFileFailed(t *testing.T) {172 buf := new(bytes.Buffer)173 mw := multipart.NewWriter(buf)174 mw.Close()175 c, _ := CreateTestContext(httptest.NewRecorder())176 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)177 c.Request.Header.Set("Content-Type", mw.FormDataContentType())178 c.engine.MaxMultipartMemory = 8 << 20179 f, err := c.FormFile("file")180 require.Error(t, err)181 assert.Nil(t, f)182}183184func TestContextMultipartForm(t *testing.T) {185 buf := new(bytes.Buffer)186 mw := multipart.NewWriter(buf)187 require.NoError(t, mw.WriteField("foo", "bar"))188 w, err := mw.CreateFormFile("file", "test")189 require.NoError(t, err)190 _, err = w.Write([]byte("test"))191 require.NoError(t, err)192 mw.Close()193 c, _ := CreateTestContext(httptest.NewRecorder())194 c.Request, _ = http.NewRequest(http.MethodPost, "/", buf)195 c.Request.Header.Set("Content-Type", mw.FormDataContentType())196 f, err := c.MultipartForm()197 require.NoError(t, err)198 assert.NotNil(t, f)199200 require.NoError(t, c.SaveUploadedFile(f.File["file"][0], "test"))201}202203func TestSaveUploadedOpenFailed(t *testing.T) {204 buf := new(bytes.Buffer)205 mw := multipart.NewWriter(buf)206 mw.Close()207208 c, _ := CreateTestContext(httptest.NewRecorder())209 c.Request, _ = http.NewRequest(http.MethodPost, "/", buf)210 c.Request.Header.Set("Content-Type", mw.FormDataContentType())211212 f := &multipart.FileHeader{213 Filename: "file",214 }215 require.Error(t, c.SaveUploadedFile(f, "test"))216}217218func TestSaveUploadedCreateFailed(t *testing.T) {219 buf := new(bytes.Buffer)220 mw := multipart.NewWriter(buf)221 w, err := mw.CreateFormFile("file", "test")222 require.NoError(t, err)223 _, err = w.Write([]byte("test"))224 require.NoError(t, err)225 mw.Close()226 c, _ := CreateTestContext(httptest.NewRecorder())227 c.Request, _ = http.NewRequest(http.MethodPost, "/", buf)228 c.Request.Header.Set("Content-Type", mw.FormDataContentType())229 f, err := c.FormFile("file")230 require.NoError(t, err)231 assert.Equal(t, "test", f.Filename)232233 require.Error(t, c.SaveUploadedFile(f, "/"))234}235236func TestSaveUploadedFileWithPermission(t *testing.T) {237 buf := new(bytes.Buffer)238 mw := multipart.NewWriter(buf)239 w, err := mw.CreateFormFile("file", "permission_test")240 require.NoError(t, err)241 _, err = w.Write([]byte("permission_test"))242 require.NoError(t, err)243 mw.Close()244 c, _ := CreateTestContext(httptest.NewRecorder())245 c.Request, _ = http.NewRequest(http.MethodPost, "/", buf)246 c.Request.Header.Set("Content-Type", mw.FormDataContentType())247 f, err := c.FormFile("file")248 require.NoError(t, err)249 assert.Equal(t, "permission_test", f.Filename)250 var mode fs.FileMode = 0o755251 dst := filepath.Join(t.TempDir(), "subdir", "permission_test")252 require.NoError(t, c.SaveUploadedFile(f, dst, mode))253 info, err := os.Stat(filepath.Dir(dst))254 require.NoError(t, err)255 assert.Equal(t, mode, info.Mode().Perm())256}257258func TestSaveUploadedFileWithPermissionFailed(t *testing.T) {259 buf := new(bytes.Buffer)260 mw := multipart.NewWriter(buf)261 w, err := mw.CreateFormFile("file", "permission_test")262 require.NoError(t, err)263 _, err = w.Write([]byte("permission_test"))264 require.NoError(t, err)265 mw.Close()266 c, _ := CreateTestContext(httptest.NewRecorder())267 c.Request, _ = http.NewRequest(http.MethodPost, "/", buf)268 c.Request.Header.Set("Content-Type", mw.FormDataContentType())269 f, err := c.FormFile("file")270 require.NoError(t, err)271 assert.Equal(t, "permission_test", f.Filename)272 var mode fs.FileMode = 0o644273 dst := filepath.Join(t.TempDir(), "test", "permission_test")274 require.Error(t, c.SaveUploadedFile(f, dst, mode))275}276277// TestSaveUploadedFileToExistingDir is a regression test for issue #4622.278// SaveUploadedFile must not call os.Chmod on a directory that already exists,279// because the process may not own it (e.g. /tmp on Linux/macOS), where chmod280// fails with "operation not permitted". This asserts the behavioral contract281// directly — a pre-existing directory's permissions are left unchanged — so it282// catches the regression on every platform, including environments (root/CI,283// user-owned $TMPDIR) where chmod on the temp dir would otherwise succeed.284func TestSaveUploadedFileToExistingDir(t *testing.T) {285 buf := new(bytes.Buffer)286 mw := multipart.NewWriter(buf)287 w, err := mw.CreateFormFile("file", "existing_dir_test")288 require.NoError(t, err)289 _, err = w.Write([]byte("existing_dir_test"))290 require.NoError(t, err)291 mw.Close()292293 c, _ := CreateTestContext(httptest.NewRecorder())294 c.Request, _ = http.NewRequest(http.MethodPost, "/", buf)295 c.Request.Header.Set("Content-Type", mw.FormDataContentType())296 f, err := c.FormFile("file")297 require.NoError(t, err)298299 // A pre-existing directory owned by this process, set to a known mode.300 dir := t.TempDir()301 require.NoError(t, os.Chmod(dir, 0o700))302303 // Pass a perm that differs from the directory's current mode. The fix must304 // not apply it to the pre-existing directory; the old code chmod'd it305 // unconditionally, which also failed outright on unowned dirs like /tmp.306 dst := filepath.Join(dir, "existing_dir_test.txt")307 require.NoError(t, c.SaveUploadedFile(f, dst, 0o755))308309 // The pre-existing directory's permissions must be unchanged.310 info, err := os.Stat(dir)311 require.NoError(t, err)312 assert.Equal(t, os.FileMode(0o700), info.Mode().Perm(),313 "permissions of a pre-existing directory must not be modified")314315 // The file must still be written with the correct content.316 content, err := os.ReadFile(dst)317 require.NoError(t, err)318 assert.Equal(t, "existing_dir_test", string(content))319}320321func TestContextReset(t *testing.T) {322 router := New()323 c := router.allocateContext(0)324 assert.Equal(t, c.engine, router)325326 c.index = 2327 c.Writer = &responseWriter{ResponseWriter: httptest.NewRecorder()}328 c.Params = Params{Param{}}329 c.Error(errors.New("test")) //nolint: errcheck330 c.Set("foo", "bar")331 c.reset()332333 assert.False(t, c.IsAborted())334 assert.Nil(t, c.Keys)335 assert.Nil(t, c.Accepted)336 assert.Empty(t, c.Errors)337 assert.Empty(t, c.Errors.Errors())338 assert.Empty(t, c.Errors.ByType(ErrorTypeAny))339 assert.Empty(t, c.Params)340 assert.EqualValues(t, -1, c.index)341 assert.Equal(t, c.Writer.(*responseWriter), &c.writermem)342}343344func TestContextHandlers(t *testing.T) {345 c, _ := CreateTestContext(httptest.NewRecorder())346 assert.Nil(t, c.handlers)347 assert.Nil(t, c.handlers.Last())348349 c.handlers = HandlersChain{}350 assert.NotNil(t, c.handlers)351 assert.Nil(t, c.handlers.Last())352353 f := func(c *Context) {}354 g := func(c *Context) {}355356 c.handlers = HandlersChain{f}357 compareFunc(t, f, c.handlers.Last())358359 c.handlers = HandlersChain{f, g}360 compareFunc(t, g, c.handlers.Last())361}362363// TestContextSetGet tests that a parameter is set correctly on the364// current context and can be retrieved using Get.365func TestContextSetGet(t *testing.T) {366 c, _ := CreateTestContext(httptest.NewRecorder())367 c.Set("foo", "bar")368369 value, err := c.Get("foo")370 assert.Equal(t, "bar", value)371 assert.True(t, err)372373 value, err = c.Get("foo2")374 assert.Nil(t, value)375 assert.False(t, err)376377 assert.Equal(t, "bar", c.MustGet("foo"))378 assert.Panicsf(t, func() {379 c.MustGet("no_exist")380 }, "key no_exist does not exist")381}382383func TestContextSetGetAnyKey(t *testing.T) {384 c, _ := CreateTestContext(httptest.NewRecorder())385386 type key struct{}387388 tests := []struct {389 key any390 }{391 {1},392 {int32(1)},393 {int64(1)},394 {uint(1)},395 {float32(1)},396 {key{}},397 {&key{}},398 }399400 for _, tt := range tests {401 t.Run(reflect.TypeOf(tt.key).String(), func(t *testing.T) {402 c.Set(tt.key, 1)403 value, ok := c.Get(tt.key)404 assert.True(t, ok)405 assert.Equal(t, 1, value)406 })407 }408}409410func TestContextSetGetPanicsWhenKeyNotComparable(t *testing.T) {411 c, _ := CreateTestContext(httptest.NewRecorder())412413 assert.Panics(t, func() {414 c.Set([]int{1}, 1)415 c.Set(func() {}, 1)416 c.Set(make(chan int), 1)417 })418}419420func TestContextSetGetValues(t *testing.T) {421 c, _ := CreateTestContext(httptest.NewRecorder())422 c.Set("string", "this is a string")423 c.Set("int32", int32(-42))424 c.Set("int64", int64(42424242424242))425 c.Set("uint64", uint64(42))426 c.Set("float32", float32(4.2))427 c.Set("float64", 4.2)428 var a any = 1429 c.Set("intInterface", a)430431 assert.Exactly(t, "this is a string", c.MustGet("string").(string))432 assert.Exactly(t, int32(-42), c.MustGet("int32").(int32))433 assert.Exactly(t, int64(42424242424242), c.MustGet("int64").(int64))434 assert.Exactly(t, uint64(42), c.MustGet("uint64").(uint64))435 assert.InDelta(t, float32(4.2), c.MustGet("float32").(float32), 0.01)436 assert.InDelta(t, 4.2, c.MustGet("float64").(float64), 0.01)437 assert.Exactly(t, 1, c.MustGet("intInterface").(int))438}439440func TestContextGetString(t *testing.T) {441 c, _ := CreateTestContext(httptest.NewRecorder())442 c.Set("string", "this is a string")443 assert.Equal(t, "this is a string", c.GetString("string"))444}445446func TestContextSetGetBool(t *testing.T) {447 c, _ := CreateTestContext(httptest.NewRecorder())448 c.Set("bool", true)449 assert.True(t, c.GetBool("bool"))450}451452func TestSetGetDelete(t *testing.T) {453 c, _ := CreateTestContext(httptest.NewRecorder())454 key := "example-key"455 value := "example-value"456 c.Set(key, value)457 val, exists := c.Get(key)458 assert.True(t, exists)459 assert.Equal(t, val, value)460 c.Delete(key)461 _, exists = c.Get(key)462 assert.False(t, exists)463}464465func TestContextGetInt(t *testing.T) {466 c, _ := CreateTestContext(httptest.NewRecorder())467 c.Set("int", 1)468 assert.Equal(t, 1, c.GetInt("int"))469}470471func TestContextGetInt8(t *testing.T) {472 c, _ := CreateTestContext(httptest.NewRecorder())473 key := "int8"474 value := int8(0x7F)475 c.Set(key, value)476 assert.Equal(t, value, c.GetInt8(key))477}478479func TestContextGetInt16(t *testing.T) {480 c, _ := CreateTestContext(httptest.NewRecorder())481 key := "int16"482 value := int16(0x7FFF)483 c.Set(key, value)484 assert.Equal(t, value, c.GetInt16(key))485}486487func TestContextGetInt32(t *testing.T) {488 c, _ := CreateTestContext(httptest.NewRecorder())489 key := "int32"490 value := int32(0x7FFFFFFF)491 c.Set(key, value)492 assert.Equal(t, value, c.GetInt32(key))493}494495func TestContextGetInt64(t *testing.T) {496 c, _ := CreateTestContext(httptest.NewRecorder())497 c.Set("int64", int64(42424242424242))498 assert.Equal(t, int64(42424242424242), c.GetInt64("int64"))499}500501func TestContextGetUint(t *testing.T) {502 c, _ := CreateTestContext(httptest.NewRecorder())503 c.Set("uint", uint(1))504 assert.Equal(t, uint(1), c.GetUint("uint"))505}506507func TestContextGetUint8(t *testing.T) {508 c, _ := CreateTestContext(httptest.NewRecorder())509 key := "uint8"510 value := uint8(0xFF)511 c.Set(key, value)512 assert.Equal(t, value, c.GetUint8(key))513}514515func TestContextGetUint16(t *testing.T) {516 c, _ := CreateTestContext(httptest.NewRecorder())517 key := "uint16"518 value := uint16(0xFFFF)519 c.Set(key, value)520 assert.Equal(t, value, c.GetUint16(key))521}522523func TestContextGetUint32(t *testing.T) {524 c, _ := CreateTestContext(httptest.NewRecorder())525 key := "uint32"526 value := uint32(0xFFFFFFFF)527 c.Set(key, value)528 assert.Equal(t, value, c.GetUint32(key))529}530531func TestContextGetUint64(t *testing.T) {532 c, _ := CreateTestContext(httptest.NewRecorder())533 c.Set("uint64", uint64(18446744073709551615))534 assert.Equal(t, uint64(18446744073709551615), c.GetUint64("uint64"))535}536537func TestContextGetFloat32(t *testing.T) {538 c, _ := CreateTestContext(httptest.NewRecorder())539 key := "float32"540 value := float32(3.14)541 c.Set(key, value)542 assert.InDelta(t, value, c.GetFloat32(key), 0.01)543}544545func TestContextGetFloat64(t *testing.T) {546 c, _ := CreateTestContext(httptest.NewRecorder())547 c.Set("float64", 4.2)548 assert.InDelta(t, 4.2, c.GetFloat64("float64"), 0.01)549}550551func TestContextGetTime(t *testing.T) {552 c, _ := CreateTestContext(httptest.NewRecorder())553 t1, _ := time.Parse("1/2/2006 15:04:05", "01/01/2017 12:00:00")554 c.Set("time", t1)555 assert.Equal(t, t1, c.GetTime("time"))556}557558func TestContextGetDuration(t *testing.T) {559 c, _ := CreateTestContext(httptest.NewRecorder())560 c.Set("duration", time.Second)561 assert.Equal(t, time.Second, c.GetDuration("duration"))562}563564func TestContextGetError(t *testing.T) {565 c, _ := CreateTestContext(httptest.NewRecorder())566 key := "error"567 value := errors.New("test error")568 c.Set(key, value)569 assert.Equal(t, value, c.GetError(key))570}571572func TestContextGetIntSlice(t *testing.T) {573 c, _ := CreateTestContext(httptest.NewRecorder())574 key := "int-slice"575 value := []int{1, 2}576 c.Set(key, value)577 assert.Equal(t, value, c.GetIntSlice(key))578}579580func TestContextGetInt8Slice(t *testing.T) {581 c, _ := CreateTestContext(httptest.NewRecorder())582 key := "int8-slice"583 value := []int8{1, 2}584 c.Set(key, value)585 assert.Equal(t, value, c.GetInt8Slice(key))586}587588func TestContextGetInt16Slice(t *testing.T) {589 c, _ := CreateTestContext(httptest.NewRecorder())590 key := "int16-slice"591 value := []int16{1, 2}592 c.Set(key, value)593 assert.Equal(t, value, c.GetInt16Slice(key))594}595596func TestContextGetInt32Slice(t *testing.T) {597 c, _ := CreateTestContext(httptest.NewRecorder())598 key := "int32-slice"599 value := []int32{1, 2}600 c.Set(key, value)601 assert.Equal(t, value, c.GetInt32Slice(key))602}603604func TestContextGetInt64Slice(t *testing.T) {605 c, _ := CreateTestContext(httptest.NewRecorder())606 key := "int64-slice"607 value := []int64{1, 2}608 c.Set(key, value)609 assert.Equal(t, value, c.GetInt64Slice(key))610}611612func TestContextGetUintSlice(t *testing.T) {613 c, _ := CreateTestContext(httptest.NewRecorder())614 key := "uint-slice"615 value := []uint{1, 2}616 c.Set(key, value)617 assert.Equal(t, value, c.GetUintSlice(key))618}619620func TestContextGetUint8Slice(t *testing.T) {621 c, _ := CreateTestContext(httptest.NewRecorder())622 key := "uint8-slice"623 value := []uint8{1, 2}624 c.Set(key, value)625 assert.Equal(t, value, c.GetUint8Slice(key))626}627628func TestContextGetUint16Slice(t *testing.T) {629 c, _ := CreateTestContext(httptest.NewRecorder())630 key := "uint16-slice"631 value := []uint16{1, 2}632 c.Set(key, value)633 assert.Equal(t, value, c.GetUint16Slice(key))634}635636func TestContextGetUint32Slice(t *testing.T) {637 c, _ := CreateTestContext(httptest.NewRecorder())638 key := "uint32-slice"639 value := []uint32{1, 2}640 c.Set(key, value)641 assert.Equal(t, value, c.GetUint32Slice(key))642}643644func TestContextGetUint64Slice(t *testing.T) {645 c, _ := CreateTestContext(httptest.NewRecorder())646 key := "uint64-slice"647 value := []uint64{1, 2}648 c.Set(key, value)649 assert.Equal(t, value, c.GetUint64Slice(key))650}651652func TestContextGetFloat32Slice(t *testing.T) {653 c, _ := CreateTestContext(httptest.NewRecorder())654 key := "float32-slice"655 value := []float32{1, 2}656 c.Set(key, value)657 assert.Equal(t, value, c.GetFloat32Slice(key))658}659660func TestContextGetFloat64Slice(t *testing.T) {661 c, _ := CreateTestContext(httptest.NewRecorder())662 key := "float64-slice"663 value := []float64{1, 2}664 c.Set(key, value)665 assert.Equal(t, value, c.GetFloat64Slice(key))666}667668func TestContextGetStringSlice(t *testing.T) {669 c, _ := CreateTestContext(httptest.NewRecorder())670 c.Set("slice", []string{"foo"})671 assert.Equal(t, []string{"foo"}, c.GetStringSlice("slice"))672}673674func TestContextGetErrorSlice(t *testing.T) {675 c, _ := CreateTestContext(httptest.NewRecorder())676 key := "error-slice"677 value := []error{errors.New("error1"), errors.New("error2")}678 c.Set(key, value)679 assert.Equal(t, value, c.GetErrorSlice(key))680}681682func TestContextGetStringMap(t *testing.T) {683 c, _ := CreateTestContext(httptest.NewRecorder())684 m := make(map[string]any)685 m["foo"] = 1686 c.Set("map", m)687688 assert.Equal(t, m, c.GetStringMap("map"))689 assert.Equal(t, 1, c.GetStringMap("map")["foo"])690}691692func TestContextGetStringMapString(t *testing.T) {693 c, _ := CreateTestContext(httptest.NewRecorder())694 m := make(map[string]string)695 m["foo"] = "bar"696 c.Set("map", m)697698 assert.Equal(t, m, c.GetStringMapString("map"))699 assert.Equal(t, "bar", c.GetStringMapString("map")["foo"])700}701702func TestContextGetStringMapStringSlice(t *testing.T) {703 c, _ := CreateTestContext(httptest.NewRecorder())704 m := make(map[string][]string)705 m["foo"] = []string{"foo"}706 c.Set("map", m)707708 assert.Equal(t, m, c.GetStringMapStringSlice("map"))709 assert.Equal(t, []string{"foo"}, c.GetStringMapStringSlice("map")["foo"])710}711712func TestCopyConcurrentWithSet(t *testing.T) {713 c := &Context{}714 var wg sync.WaitGroup715 wg.Add(2)716 go func() {717 defer wg.Done()718 for i := 0; i < 100; i++ {719 c.Set(i, i)720 }721 }()722 go func() {723 defer wg.Done()724 for i := 0; i < 100; i++ {725 cp := c.Copy()726 for k, v := range cp.Keys {727 if k != v {728 t.Errorf("copied key %v = %v, want %v", k, v, k)729 }730 }731 }732 }()733 wg.Wait()734}735736func TestContextCopy(t *testing.T) {737 c, _ := CreateTestContext(httptest.NewRecorder())738 c.index = 2739 c.Request, _ = http.NewRequest(http.MethodPost, "/hola", nil)740 c.handlers = HandlersChain{func(c *Context) {}}741 c.Params = Params{Param{Key: "foo", Value: "bar"}}742 c.Set("foo", "bar")743 c.fullPath = "/hola"744745 cp := c.Copy()746 assert.Nil(t, cp.handlers)747 assert.Nil(t, cp.writermem.ResponseWriter)748 assert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))749 assert.Equal(t, cp.Request, c.Request)750 assert.Equal(t, abortIndex, cp.index)751 assert.Equal(t, cp.Keys, c.Keys)752 assert.Equal(t, cp.engine, c.engine)753 assert.Equal(t, cp.Params, c.Params)754 cp.Set("foo", "notBar")755 assert.NotEqual(t, cp.Keys["foo"], c.Keys["foo"])756 assert.Equal(t, cp.fullPath, c.fullPath)757}758759func TestContextCopyCopiesErrors(t *testing.T) {760 c, _ := CreateTestContext(httptest.NewRecorder())761 c.Request, _ = http.NewRequest(http.MethodGet, "/", nil)762 _ = c.Error(errors.New("first error"))763 _ = c.Error(errors.New("second error"))764765 cp := c.Copy()766767 // copied context has the same errors768 assert.Len(t, cp.Errors, 2)769 assert.Equal(t, c.Errors[0].Error(), cp.Errors[0].Error())770 assert.Equal(t, c.Errors[1].Error(), cp.Errors[1].Error())771772 // mutations on the copy do not affect the original773 _ = cp.Error(errors.New("third error"))774 assert.Len(t, c.Errors, 2)775 assert.Len(t, cp.Errors, 3)776}777778func TestContextCopyCopiesAccepted(t *testing.T) {779 c, _ := CreateTestContext(httptest.NewRecorder())780 c.Request, _ = http.NewRequest(http.MethodGet, "/", nil)781 c.SetAccepted("application/json", "text/html")782783 cp := c.Copy()784785 assert.Equal(t, c.Accepted, cp.Accepted)786787 // mutations on the copy do not affect the original788 cp.SetAccepted("text/plain")789 assert.Equal(t, []string{"application/json", "text/html"}, c.Accepted)790 assert.Equal(t, []string{"text/plain"}, cp.Accepted)791}792793func TestContextCopyNilErrorsAndAccepted(t *testing.T) {794 c, _ := CreateTestContext(httptest.NewRecorder())795 c.Request, _ = http.NewRequest(http.MethodGet, "/", nil)796797 cp := c.Copy()798799 assert.Nil(t, cp.Errors)800 assert.Nil(t, cp.Accepted)801}802803func TestContextHandlerName(t *testing.T) {804 c, _ := CreateTestContext(httptest.NewRecorder())805 c.handlers = HandlersChain{func(c *Context) {}, handlerNameTest}806807 assert.Regexp(t, "^(.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest$", c.HandlerName())808}809810func TestContextHandlerNames(t *testing.T) {811 c, _ := CreateTestContext(httptest.NewRecorder())812 c.handlers = HandlersChain{func(c *Context) {}, nil, handlerNameTest, func(c *Context) {}, handlerNameTest2}813814 names := c.HandlerNames()815816 assert.Len(t, names, 4)817 for _, name := range names {818 assert.Regexp(t, `^(.*/vendor/)?(github\.com/gin-gonic/gin\.){1}(TestContextHandlerNames\.func.*){0,1}(handlerNameTest.*){0,1}`, name)819 }820}821822func handlerNameTest(c *Context) {823}824825func handlerNameTest2(c *Context) {826}827828var handlerTest HandlerFunc = func(c *Context) {829}830831func TestContextHandler(t *testing.T) {832 c, _ := CreateTestContext(httptest.NewRecorder())833 c.handlers = HandlersChain{func(c *Context) {}, handlerTest}834835 assert.Equal(t, reflect.ValueOf(handlerTest).Pointer(), reflect.ValueOf(c.Handler()).Pointer())836}837838func TestContextQuery(t *testing.T) {839 c, _ := CreateTestContext(httptest.NewRecorder())840 c.Request, _ = http.NewRequest(http.MethodGet, "http://example.com/?foo=bar&page=10&id=", nil)841842 value, ok := c.GetQuery("foo")843 assert.True(t, ok)844 assert.Equal(t, "bar", value)845 assert.Equal(t, "bar", c.DefaultQuery("foo", "none"))846 assert.Equal(t, "bar", c.Query("foo"))847848 value, ok = c.GetQuery("page")849 assert.True(t, ok)850 assert.Equal(t, "10", value)851 assert.Equal(t, "10", c.DefaultQuery("page", "0"))852 assert.Equal(t, "10", c.Query("page"))853854 value, ok = c.GetQuery("id")855 assert.True(t, ok)856 assert.Empty(t, value)857 assert.Empty(t, c.DefaultQuery("id", "nada"))858 assert.Empty(t, c.Query("id"))859860 value, ok = c.GetQuery("NoKey")861 assert.False(t, ok)862 assert.Empty(t, value)863 assert.Equal(t, "nada", c.DefaultQuery("NoKey", "nada"))864 assert.Empty(t, c.Query("NoKey"))865866 // postform should not mess867 value, ok = c.GetPostForm("page")868 assert.False(t, ok)869 assert.Empty(t, value)870 assert.Empty(t, c.PostForm("foo"))871}872873func TestContextInitQueryCache(t *testing.T) {874 validURL, err := url.Parse("https://github.com/gin-gonic/gin/pull/3969?key=value&otherkey=othervalue")875 require.NoError(t, err)876877 tests := []struct {878 testName string879 testContext *Context880 expectedQueryCache url.Values881 }{882 {883 testName: "queryCache should remain unchanged if already not nil",884 testContext: &Context{885 queryCache: url.Values{"a": []string{"b"}},886 Request: &http.Request{URL: validURL}, // valid request for evidence that values weren't extracted887 },888 expectedQueryCache: url.Values{"a": []string{"b"}},889 },890 {891 testName: "queryCache should be empty when Request is nil",892 testContext: &Context{Request: nil}, // explicit nil for readability893 expectedQueryCache: url.Values{},894 },895 {896 testName: "queryCache should be empty when Request.URL is nil",897 testContext: &Context{Request: &http.Request{URL: nil}}, // explicit nil for readability898 expectedQueryCache: url.Values{},899 },900 {901 testName: "queryCache should be populated when it not yet populated and Request + Request.URL are non nil",902 testContext: &Context{Request: &http.Request{URL: validURL}}, // explicit nil for readability903 expectedQueryCache: url.Values{"key": []string{"value"}, "otherkey": []string{"othervalue"}},904 },905 }906907 for _, test := range tests {908 t.Run(test.testName, func(t *testing.T) {909 test.testContext.initQueryCache()910 assert.Equal(t, test.expectedQueryCache, test.testContext.queryCache)911 })912 }913}914915func TestContextDefaultQueryOnEmptyRequest(t *testing.T) {916 c, _ := CreateTestContext(httptest.NewRecorder()) // here c.Request == nil917 assert.NotPanics(t, func() {918 value, ok := c.GetQuery("NoKey")919 assert.False(t, ok)920 assert.Empty(t, value)921 })922 assert.NotPanics(t, func() {923 assert.Equal(t, "nada", c.DefaultQuery("NoKey", "nada"))924 })925 assert.NotPanics(t, func() {926 assert.Empty(t, c.Query("NoKey"))927 })928}929930func TestContextQueryAndPostForm(t *testing.T) {931 c, _ := CreateTestContext(httptest.NewRecorder())932 body := strings.NewReader("foo=bar&page=11&both=&foo=second")933 c.Request, _ = http.NewRequest(http.MethodPost,934 "/?both=GET&id=main&id=omit&array[]=first&array[]=second&ids[a]=hi&ids[b]=3.14", body)935 c.Request.Header.Add("Content-Type", MIMEPOSTForm)936937 assert.Equal(t, "bar", c.DefaultPostForm("foo", "none"))938 assert.Equal(t, "bar", c.PostForm("foo"))939 assert.Empty(t, c.Query("foo"))940941 value, ok := c.GetPostForm("page")942 assert.True(t, ok)943 assert.Equal(t, "11", value)944 assert.Equal(t, "11", c.DefaultPostForm("page", "0"))945 assert.Equal(t, "11", c.PostForm("page"))946 assert.Empty(t, c.Query("page"))947948 value, ok = c.GetPostForm("both")949 assert.True(t, ok)950 assert.Empty(t, value)951 assert.Empty(t, c.PostForm("both"))952 assert.Empty(t, c.DefaultPostForm("both", "nothing"))953 assert.Equal(t, http.MethodGet, c.Query("both"), http.MethodGet)954955 value, ok = c.GetQuery("id")956 assert.True(t, ok)957 assert.Equal(t, "main", value)958 assert.Equal(t, "000", c.DefaultPostForm("id", "000"))959 assert.Equal(t, "main", c.Query("id"))960 assert.Empty(t, c.PostForm("id"))961962 value, ok = c.GetQuery("NoKey")963 assert.False(t, ok)964 assert.Empty(t, value)965 value, ok = c.GetPostForm("NoKey")966 assert.False(t, ok)967 assert.Empty(t, value)968 assert.Equal(t, "nada", c.DefaultPostForm("NoKey", "nada"))969 assert.Equal(t, "nothing", c.DefaultQuery("NoKey", "nothing"))970 assert.Empty(t, c.PostForm("NoKey"))971 assert.Empty(t, c.Query("NoKey"))972973 var obj struct {974 Foo string `form:"foo"`975 ID string `form:"id"`976 Page int `form:"page"`977 Both string `form:"both"`978 Array []string `form:"array[]"`979 }980 require.NoError(t, c.Bind(&obj))981 assert.Equal(t, "bar", obj.Foo, "bar")982 assert.Equal(t, "main", obj.ID, "main")983 assert.Equal(t, 11, obj.Page, 11)984 assert.Empty(t, obj.Both)985 assert.Equal(t, []string{"first", "second"}, obj.Array)986987 values, ok := c.GetQueryArray("array[]")988 assert.True(t, ok)989 assert.Equal(t, "first", values[0])990 assert.Equal(t, "second", values[1])991992 values = c.QueryArray("array[]")993 assert.Equal(t, "first", values[0])994 assert.Equal(t, "second", values[1])995996 values = c.QueryArray("nokey")997 assert.Empty(t, values)998999 values = c.QueryArray("both")1000 assert.Len(t, values, 1)1001 assert.Equal(t, http.MethodGet, values[0])10021003 dicts, ok := c.GetQueryMap("ids")1004 assert.True(t, ok)1005 assert.Equal(t, "hi", dicts["a"])1006 assert.Equal(t, "3.14", dicts["b"])10071008 dicts, ok = c.GetQueryMap("nokey")1009 assert.False(t, ok)1010 assert.Empty(t, dicts)10111012 dicts, ok = c.GetQueryMap("both")1013 assert.False(t, ok)1014 assert.Empty(t, dicts)10151016 dicts, ok = c.GetQueryMap("array")1017 assert.False(t, ok)1018 assert.Empty(t, dicts)10191020 dicts = c.QueryMap("ids")1021 assert.Equal(t, "hi", dicts["a"])1022 assert.Equal(t, "3.14", dicts["b"])10231024 dicts = c.QueryMap("nokey")1025 assert.Empty(t, dicts)1026}10271028func TestContextPostFormMultipart(t *testing.T) {1029 c, _ := CreateTestContext(httptest.NewRecorder())1030 c.Request = createMultipartRequest()10311032 var obj struct {1033 Foo string `form:"foo"`1034 Bar string `form:"bar"`1035 BarAsInt int `form:"bar"`1036 Array []string `form:"array"`1037 ID string `form:"id"`1038 TimeLocal time.Time `form:"time_local" time_format:"02/01/2006 15:04"`1039 TimeUTC time.Time `form:"time_utc" time_format:"02/01/2006 15:04" time_utc:"1"`1040 TimeLocation time.Time `form:"time_location" time_format:"02/01/2006 15:04" time_location:"Asia/Tokyo"`1041 BlankTime time.Time `form:"blank_time" time_format:"02/01/2006 15:04"`1042 }1043 require.NoError(t, c.Bind(&obj))1044 assert.Equal(t, "bar", obj.Foo)1045 assert.Equal(t, "10", obj.Bar)1046 assert.Equal(t, 10, obj.BarAsInt)1047 assert.Equal(t, []string{"first", "second"}, obj.Array)1048 assert.Empty(t, obj.ID)1049 assert.Equal(t, "31/12/2016 14:55", obj.TimeLocal.Format("02/01/2006 15:04"))1050 assert.Equal(t, time.Local, obj.TimeLocal.Location())1051 assert.Equal(t, "31/12/2016 14:55", obj.TimeUTC.Format("02/01/2006 15:04"))1052 assert.Equal(t, time.UTC, obj.TimeUTC.Location())1053 loc, _ := time.LoadLocation("Asia/Tokyo")1054 assert.Equal(t, "31/12/2016 14:55", obj.TimeLocation.Format("02/01/2006 15:04"))1055 assert.Equal(t, loc, obj.TimeLocation.Location())1056 assert.True(t, obj.BlankTime.IsZero())10571058 value, ok := c.GetQuery("foo")1059 assert.False(t, ok)1060 assert.Empty(t, value)1061 assert.Empty(t, c.Query("bar"))1062 assert.Equal(t, "nothing", c.DefaultQuery("id", "nothing"))10631064 value, ok = c.GetPostForm("foo")1065 assert.True(t, ok)1066 assert.Equal(t, "bar", value)1067 assert.Equal(t, "bar", c.PostForm("foo"))10681069 value, ok = c.GetPostForm("array")1070 assert.True(t, ok)1071 assert.Equal(t, "first", value)1072 assert.Equal(t, "first", c.PostForm("array"))10731074 assert.Equal(t, "10", c.DefaultPostForm("bar", "nothing"))10751076 value, ok = c.GetPostForm("id")1077 assert.True(t, ok)1078 assert.Empty(t, value)1079 assert.Empty(t, c.PostForm("id"))1080 assert.Empty(t, c.DefaultPostForm("id", "nothing"))10811082 value, ok = c.GetPostForm("nokey")1083 assert.False(t, ok)1084 assert.Empty(t, value)1085 assert.Equal(t, "nothing", c.DefaultPostForm("nokey", "nothing"))10861087 values, ok := c.GetPostFormArray("array")1088 assert.True(t, ok)1089 assert.Equal(t, "first", values[0])1090 assert.Equal(t, "second", values[1])10911092 values = c.PostFormArray("array")1093 assert.Equal(t, "first", values[0])1094 assert.Equal(t, "second", values[1])10951096 values = c.PostFormArray("nokey")1097 assert.Empty(t, values)10981099 values = c.PostFormArray("foo")1100 assert.Len(t, values, 1)1101 assert.Equal(t, "bar", values[0])11021103 dicts, ok := c.GetPostFormMap("names")1104 assert.True(t, ok)1105 assert.Equal(t, "thinkerou", dicts["a"])1106 assert.Equal(t, "tianou", dicts["b"])11071108 dicts, ok = c.GetPostFormMap("nokey")1109 assert.False(t, ok)1110 assert.Empty(t, dicts)11111112 dicts = c.PostFormMap("names")1113 assert.Equal(t, "thinkerou", dicts["a"])1114 assert.Equal(t, "tianou", dicts["b"])11151116 dicts = c.PostFormMap("nokey")1117 assert.Empty(t, dicts)1118}11191120func TestContextSetCookie(t *testing.T) {1121 c, _ := CreateTestContext(httptest.NewRecorder())1122 c.SetSameSite(http.SameSiteLaxMode)1123 c.SetCookie("user", "gin", 1, "/", "localhost", true, true)1124 assert.Equal(t, "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure; SameSite=Lax", c.Writer.Header().Get("Set-Cookie"))1125}11261127func TestContextSetCookiePathEmpty(t *testing.T) {1128 c, _ := CreateTestContext(httptest.NewRecorder())1129 c.SetSameSite(http.SameSiteLaxMode)1130 c.SetCookie("user", "gin", 1, "", "localhost", true, true)1131 assert.Equal(t, "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure; SameSite=Lax", c.Writer.Header().Get("Set-Cookie"))1132}11331134func TestContextGetCookie(t *testing.T) {1135 c, _ := CreateTestContext(httptest.NewRecorder())1136 c.Request, _ = http.NewRequest(http.MethodGet, "/get", nil)1137 c.Request.Header.Set("Cookie", "user=gin")1138 cookie, _ := c.Cookie("user")1139 assert.Equal(t, "gin", cookie)11401141 _, err := c.Cookie("nokey")1142 require.Error(t, err)1143}11441145func TestContextBodyAllowedForStatus(t *testing.T) {1146 assert.False(t, bodyAllowedForStatus(http.StatusContinue))1147 assert.False(t, bodyAllowedForStatus(http.StatusProcessing))1148 assert.False(t, bodyAllowedForStatus(http.StatusNoContent))1149 assert.False(t, bodyAllowedForStatus(http.StatusNotModified))1150 assert.True(t, bodyAllowedForStatus(http.StatusInternalServerError))1151}11521153type TestRender struct{}11541155func (*TestRender) Render(http.ResponseWriter) error {1156 return errTestRender1157}11581159func (*TestRender) WriteContentType(http.ResponseWriter) {}11601161func TestContextRenderIfErr(t *testing.T) {1162 w := httptest.NewRecorder()1163 c, _ := CreateTestContext(w)11641165 c.Render(http.StatusOK, &TestRender{})11661167 assert.Equal(t, errorMsgs{&Error{Err: errTestRender, Type: 1}}, c.Errors)1168}11691170// Tests that the response is serialized as JSON1171// and Content-Type is set to application/json1172// and special HTML characters are escaped1173func TestContextRenderJSON(t *testing.T) {1174 w := httptest.NewRecorder()1175 c, _ := CreateTestContext(w)11761177 c.JSON(http.StatusCreated, H{"foo": "bar", "html": "<b>"})11781179 assert.Equal(t, http.StatusCreated, w.Code)1180 assert.JSONEq(t, "{\"foo\":\"bar\",\"html\":\"\\u003cb\\u003e\"}", w.Body.String())1181 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))1182}11831184// Tests that the response is serialized as JSONP1185// and Content-Type is set to application/javascript1186func TestContextRenderJSONP(t *testing.T) {1187 w := httptest.NewRecorder()1188 c, _ := CreateTestContext(w)1189 c.Request, _ = http.NewRequest(http.MethodGet, "http://example.com/?callback=x", nil)11901191 c.JSONP(http.StatusCreated, H{"foo": "bar"})11921193 assert.Equal(t, http.StatusCreated, w.Code)1194 assert.Equal(t, "x({\"foo\":\"bar\"});", w.Body.String())1195 assert.Equal(t, "application/javascript; charset=utf-8", w.Header().Get("Content-Type"))1196}11971198// Tests that the response is serialized as JSONP1199// and Content-Type is set to application/json1200func TestContextRenderJSONPWithoutCallback(t *testing.T) {1201 w := httptest.NewRecorder()1202 c, _ := CreateTestContext(w)1203 c.Request, _ = http.NewRequest(http.MethodGet, "http://example.com", nil)12041205 c.JSONP(http.StatusCreated, H{"foo": "bar"})12061207 assert.Equal(t, http.StatusCreated, w.Code)1208 assert.JSONEq(t, `{"foo":"bar"}`, w.Body.String())1209 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))1210}12111212// Tests that no JSON is rendered if code is 2041213func TestContextRenderNoContentJSON(t *testing.T) {1214 w := httptest.NewRecorder()1215 c, _ := CreateTestContext(w)12161217 c.JSON(http.StatusNoContent, H{"foo": "bar"})12181219 assert.Equal(t, http.StatusNoContent, w.Code)1220 assert.Empty(t, w.Body.String())1221 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))1222}12231224// Tests that the response is serialized as JSON1225// we change the content-type before1226func TestContextRenderAPIJSON(t *testing.T) {1227 w := httptest.NewRecorder()1228 c, _ := CreateTestContext(w)12291230 c.Header("Content-Type", "application/vnd.api+json")1231 c.JSON(http.StatusCreated, H{"foo": "bar"})12321233 assert.Equal(t, http.StatusCreated, w.Code)1234 assert.JSONEq(t, `{"foo":"bar"}`, w.Body.String())1235 assert.Equal(t, "application/vnd.api+json", w.Header().Get("Content-Type"))1236}12371238// Tests that no Custom JSON is rendered if code is 2041239func TestContextRenderNoContentAPIJSON(t *testing.T) {1240 w := httptest.NewRecorder()1241 c, _ := CreateTestContext(w)12421243 c.Header("Content-Type", "application/vnd.api+json")1244 c.JSON(http.StatusNoContent, H{"foo": "bar"})12451246 assert.Equal(t, http.StatusNoContent, w.Code)1247 assert.Empty(t, w.Body.String())1248 assert.Equal(t, "application/vnd.api+json", w.Header().Get("Content-Type"))1249}12501251// Tests that the response is serialized as JSON1252// and Content-Type is set to application/json1253func TestContextRenderIndentedJSON(t *testing.T) {1254 w := httptest.NewRecorder()1255 c, _ := CreateTestContext(w)12561257 c.IndentedJSON(http.StatusCreated, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})12581259 assert.Equal(t, http.StatusCreated, w.Code)1260 assert.JSONEq(t, "{\n \"bar\": \"foo\",\n \"foo\": \"bar\",\n \"nested\": {\n \"foo\": \"bar\"\n }\n}", w.Body.String())1261 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))1262}12631264// Tests that no Custom JSON is rendered if code is 2041265func TestContextRenderNoContentIndentedJSON(t *testing.T) {1266 w := httptest.NewRecorder()1267 c, _ := CreateTestContext(w)12681269 c.IndentedJSON(http.StatusNoContent, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})12701271 assert.Equal(t, http.StatusNoContent, w.Code)1272 assert.Empty(t, w.Body.String())1273 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))1274}12751276func TestContextClientIPWithMultipleHeaders(t *testing.T) {1277 c, _ := CreateTestContext(httptest.NewRecorder())1278 c.Request, _ = http.NewRequest(http.MethodGet, "/test", nil)12791280 // Multiple X-Forwarded-For headers1281 c.Request.Header.Add("X-Forwarded-For", "1.2.3.4, "+localhostIP)1282 c.Request.Header.Add("X-Forwarded-For", "5.6.7.8")1283 c.Request.RemoteAddr = localhostIP + ":1234"12841285 c.engine.ForwardedByClientIP = true1286 c.engine.RemoteIPHeaders = []string{"X-Forwarded-For"}1287 _ = c.engine.SetTrustedProxies([]string{localhostIP})12881289 // Should return 5.6.7.8 (last non-trusted IP)1290 assert.Equal(t, "5.6.7.8", c.ClientIP())1291}12921293func TestContextClientIPWithSingleHeader(t *testing.T) {1294 c, _ := CreateTestContext(httptest.NewRecorder())1295 c.Request, _ = http.NewRequest(http.MethodGet, "/test", nil)1296 c.Request.Header.Set("X-Forwarded-For", "1.2.3.4, "+localhostIP)1297 c.Request.RemoteAddr = localhostIP + ":1234"12981299 c.engine.ForwardedByClientIP = true1300 c.engine.RemoteIPHeaders = []string{"X-Forwarded-For"}1301 _ = c.engine.SetTrustedProxies([]string{localhostIP})13021303 // Should return 1.2.3.41304 assert.Equal(t, "1.2.3.4", c.ClientIP())1305}13061307// Tests that the response is serialized as Secure JSON1308// and Content-Type is set to application/json1309func TestContextRenderSecureJSON(t *testing.T) {1310 w := httptest.NewRecorder()1311 c, router := CreateTestContext(w)13121313 router.SecureJsonPrefix("&&&START&&&")1314 c.SecureJSON(http.StatusCreated, []string{"foo", "bar"})13151316 assert.Equal(t, http.StatusCreated, w.Code)1317 assert.Equal(t, "&&&START&&&[\"foo\",\"bar\"]", w.Body.String())1318 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))1319}13201321// Tests that no Custom JSON is rendered if code is 2041322func TestContextRenderNoContentSecureJSON(t *testing.T) {1323 w := httptest.NewRecorder()1324 c, _ := CreateTestContext(w)13251326 c.SecureJSON(http.StatusNoContent, []string{"foo", "bar"})13271328 assert.Equal(t, http.StatusNoContent, w.Code)1329 assert.Empty(t, w.Body.String())1330 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))1331}13321333func TestContextRenderNoContentAsciiJSON(t *testing.T) {1334 w := httptest.NewRecorder()1335 c, _ := CreateTestContext(w)13361337 c.AsciiJSON(http.StatusNoContent, []string{"lang", "Go语言"})13381339 assert.Equal(t, http.StatusNoContent, w.Code)1340 assert.Empty(t, w.Body.String())1341 assert.Equal(t, "application/json", w.Header().Get("Content-Type"))1342}13431344// Tests that the response is serialized as JSON1345// and Content-Type is set to application/json1346// and special HTML characters are preserved1347func TestContextRenderPureJSON(t *testing.T) {1348 w := httptest.NewRecorder()1349 c, _ := CreateTestContext(w)1350 c.PureJSON(http.StatusCreated, H{"foo": "bar", "html": "<b>"})1351 assert.Equal(t, http.StatusCreated, w.Code)1352 assert.JSONEq(t, "{\"foo\":\"bar\",\"html\":\"<b>\"}\n", w.Body.String())1353 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))1354}13551356// Tests that the response executes the templates1357// and responds with Content-Type set to text/html1358func TestContextRenderHTML(t *testing.T) {1359 w := httptest.NewRecorder()1360 c, router := CreateTestContext(w)13611362 templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))1363 router.SetHTMLTemplate(templ)13641365 c.HTML(http.StatusCreated, "t", H{"name": "alexandernyquist"})13661367 assert.Equal(t, http.StatusCreated, w.Code)1368 assert.Equal(t, "Hello alexandernyquist", w.Body.String())1369 assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))1370}13711372func TestContextRenderHTMLWithoutRenderer(t *testing.T) {1373 tests := []struct {1374 name string1375 method string1376 status int1377 wantErrors []string1378 wantAborted bool1379 wantNextCalled bool1380 }{1381 {1382 name: "body allowed",1383 method: http.MethodGet,1384 status: http.StatusAccepted,1385 wantErrors: []string{"html renderer is not configured"},1386 wantAborted: true,1387 },1388 {1389 name: "no content",1390 method: http.MethodGet,1391 status: http.StatusNoContent,1392 wantNextCalled: true,1393 },1394 {1395 name: "not modified",1396 method: http.MethodGet,1397 status: http.StatusNotModified,1398 wantNextCalled: true,1399 },1400 {1401 name: "head",1402 method: http.MethodHead,1403 status: http.StatusOK,1404 wantErrors: []string{"html renderer is not configured"},1405 wantAborted: true,1406 },1407 }14081409 for _, tt := range tests {1410 t.Run(tt.name, func(t *testing.T) {1411 w := httptest.NewRecorder()1412 router := New()1413 var contextErrors []string1414 var contextAborted bool1415 nextHandlerCalled := false14161417 handlers := []HandlerFunc{1418 func(c *Context) {1419 c.HTML(tt.status, "index.tmpl", H{"title": "Main website"})1420 contextErrors = c.Errors.Errors()1421 contextAborted = c.IsAborted()1422 },1423 func(_ *Context) {1424 nextHandlerCalled = true1425 },1426 }1427 if tt.method == http.MethodHead {1428 router.HEAD("/", handlers...)1429 } else {1430 router.GET("/", handlers...)1431 }14321433 req := httptest.NewRequest(tt.method, "/", nil)1434 require.NotPanics(t, func() {1435 router.ServeHTTP(w, req)1436 })14371438 assert.Equal(t, tt.status, w.Code)1439 assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))1440 assert.Equal(t, tt.wantErrors, contextErrors)1441 assert.Equal(t, tt.wantAborted, contextAborted)1442 assert.Equal(t, tt.wantNextCalled, nextHandlerCalled)1443 assert.Empty(t, w.Body.String())1444 })1445 }1446}14471448func TestContextRenderHTML2(t *testing.T) {1449 w := httptest.NewRecorder()1450 c, router := CreateTestContext(w)14511452 // print debug warning log when Engine.trees > 01453 router.addRoute(http.MethodGet, "/", HandlersChain{func(_ *Context) {}})1454 assert.Len(t, router.trees, 1)14551456 templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))1457 re := captureOutput(t, func() {1458 SetMode(DebugMode)1459 router.SetHTMLTemplate(templ)1460 SetMode(TestMode)1461 })14621463 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)14641465 c.HTML(http.StatusCreated, "t", H{"name": "alexandernyquist"})14661467 assert.Equal(t, http.StatusCreated, w.Code)1468 assert.Equal(t, "Hello alexandernyquist", w.Body.String())1469 assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))1470}14711472// Tests that no HTML is rendered if code is 2041473func TestContextRenderNoContentHTML(t *testing.T) {1474 w := httptest.NewRecorder()1475 c, router := CreateTestContext(w)1476 templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))1477 router.SetHTMLTemplate(templ)14781479 c.HTML(http.StatusNoContent, "t", H{"name": "alexandernyquist"})14801481 assert.Equal(t, http.StatusNoContent, w.Code)1482 assert.Empty(t, w.Body.String())1483 assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))1484}14851486// TestContextRenderXML tests that the response is serialized as XML1487// and Content-Type is set to application/xml1488func TestContextRenderXML(t *testing.T) {1489 w := httptest.NewRecorder()1490 c, _ := CreateTestContext(w)14911492 c.XML(http.StatusCreated, H{"foo": "bar"})14931494 assert.Equal(t, http.StatusCreated, w.Code)1495 assert.Equal(t, "<map><foo>bar</foo></map>", w.Body.String())1496 assert.Equal(t, "application/xml; charset=utf-8", w.Header().Get("Content-Type"))1497}14981499// Tests that no XML is rendered if code is 2041500func TestContextRenderNoContentXML(t *testing.T) {1501 w := httptest.NewRecorder()1502 c, _ := CreateTestContext(w)15031504 c.XML(http.StatusNoContent, H{"foo": "bar"})15051506 assert.Equal(t, http.StatusNoContent, w.Code)1507 assert.Empty(t, w.Body.String())1508 assert.Equal(t, "application/xml; charset=utf-8", w.Header().Get("Content-Type"))1509}15101511// TestContextRenderPDF tests that the response is serialized as PDF1512// and Content-Type is set to application/pdf1513func TestContextRenderPDF(t *testing.T) {1514 w := httptest.NewRecorder()1515 c, _ := CreateTestContext(w)15161517 data := []byte("%Test pdf content")1518 c.PDF(http.StatusCreated, data)15191520 assert.Equal(t, http.StatusCreated, w.Code)1521 assert.Equal(t, data, w.Body.Bytes())1522 assert.Equal(t, "application/pdf", w.Header().Get("Content-Type"))1523}15241525// Tests that no PDF is rendered if code is 2041526func TestContextRenderNoContentPDF(t *testing.T) {1527 w := httptest.NewRecorder()1528 c, _ := CreateTestContext(w)15291530 data := []byte("%Test pdf content")1531 c.PDF(http.StatusNoContent, data)15321533 assert.Equal(t, http.StatusNoContent, w.Code)1534 assert.Empty(t, w.Body.Bytes())1535 assert.Equal(t, "application/pdf", w.Header().Get("Content-Type"))1536}15371538// TestContextRenderString tests that the response is returned1539// with Content-Type set to text/plain1540func TestContextRenderString(t *testing.T) {1541 w := httptest.NewRecorder()1542 c, _ := CreateTestContext(w)15431544 c.String(http.StatusCreated, "test %s %d", "string", 2)15451546 assert.Equal(t, http.StatusCreated, w.Code)1547 assert.Equal(t, "test string 2", w.Body.String())1548 assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type"))1549}15501551// Tests that no String is rendered if code is 2041552func TestContextRenderNoContentString(t *testing.T) {1553 w := httptest.NewRecorder()1554 c, _ := CreateTestContext(w)15551556 c.String(http.StatusNoContent, "test %s %d", "string", 2)15571558 assert.Equal(t, http.StatusNoContent, w.Code)1559 assert.Empty(t, w.Body.String())1560 assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type"))1561}15621563// TestContextRenderHTMLString tests that the response is returned1564// with Content-Type set to text/html1565func TestContextRenderHTMLString(t *testing.T) {1566 w := httptest.NewRecorder()1567 c, _ := CreateTestContext(w)15681569 c.Header("Content-Type", "text/html; charset=utf-8")1570 c.String(http.StatusCreated, "<html>%s %d</html>", "string", 3)15711572 assert.Equal(t, http.StatusCreated, w.Code)1573 assert.Equal(t, "<html>string 3</html>", w.Body.String())1574 assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))1575}15761577// Tests that no HTML String is rendered if code is 2041578func TestContextRenderNoContentHTMLString(t *testing.T) {1579 w := httptest.NewRecorder()1580 c, _ := CreateTestContext(w)15811582 c.Header("Content-Type", "text/html; charset=utf-8")1583 c.String(http.StatusNoContent, "<html>%s %d</html>", "string", 3)15841585 assert.Equal(t, http.StatusNoContent, w.Code)1586 assert.Empty(t, w.Body.String())1587 assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))1588}15891590// TestContextRenderData tests that the response can be written from `bytestring`1591// with specified MIME type1592func TestContextRenderData(t *testing.T) {1593 w := httptest.NewRecorder()1594 c, _ := CreateTestContext(w)15951596 c.Data(http.StatusCreated, "text/csv", []byte(`foo,bar`))15971598 assert.Equal(t, http.StatusCreated, w.Code)1599 assert.Equal(t, "foo,bar", w.Body.String())1600 assert.Equal(t, "text/csv", w.Header().Get("Content-Type"))1601}16021603// Tests that no Custom Data is rendered if code is 2041604func TestContextRenderNoContentData(t *testing.T) {1605 w := httptest.NewRecorder()1606 c, _ := CreateTestContext(w)16071608 c.Data(http.StatusNoContent, "text/csv", []byte(`foo,bar`))16091610 assert.Equal(t, http.StatusNoContent, w.Code)1611 assert.Empty(t, w.Body.String())1612 assert.Equal(t, "text/csv", w.Header().Get("Content-Type"))1613}16141615func TestContextRenderSSE(t *testing.T) {1616 w := httptest.NewRecorder()1617 c, _ := CreateTestContext(w)16181619 c.SSEvent("float", 1.5)1620 c.Render(-1, sse.Event{1621 Id: "123",1622 Data: "text",1623 })1624 c.SSEvent("chat", H{1625 "foo": "bar",1626 "bar": "foo",1627 })16281629 assert.Equal(t, strings.ReplaceAll(w.Body.String(), " ", ""), strings.ReplaceAll("event:float\ndata:1.5\n\nid:123\ndata:text\n\nevent:chat\ndata:{\"bar\":\"foo\",\"foo\":\"bar\"}\n\n", " ", ""))1630}16311632func TestContextRenderFile(t *testing.T) {1633 w := httptest.NewRecorder()1634 c, _ := CreateTestContext(w)16351636 c.Request, _ = http.NewRequest(http.MethodGet, "/", nil)1637 c.File("./gin.go")16381639 assert.Equal(t, http.StatusOK, w.Code)1640 assert.Contains(t, w.Body.String(), "func New(opts ...OptionFunc) *Engine {")1641 // Content-Type='text/plain; charset=utf-8' when go version <= 1.16,1642 // else, Content-Type='text/x-go; charset=utf-8'1643 assert.NotEmpty(t, w.Header().Get("Content-Type"))1644}16451646func TestContextRenderFileFromFS(t *testing.T) {1647 w := httptest.NewRecorder()1648 c, _ := CreateTestContext(w)16491650 c.Request, _ = http.NewRequest(http.MethodGet, "/some/path", nil)1651 c.FileFromFS("./gin.go", Dir(".", false))16521653 assert.Equal(t, http.StatusOK, w.Code)1654 assert.Contains(t, w.Body.String(), "func New(opts ...OptionFunc) *Engine {")1655 // Content-Type='text/plain; charset=utf-8' when go version <= 1.16,1656 // else, Content-Type='text/x-go; charset=utf-8'1657 assert.NotEmpty(t, w.Header().Get("Content-Type"))1658 assert.Equal(t, "/some/path", c.Request.URL.Path)1659}16601661func TestContextRenderAttachment(t *testing.T) {1662 w := httptest.NewRecorder()1663 c, _ := CreateTestContext(w)1664 newFilename := "new_filename.go"16651666 c.Request, _ = http.NewRequest(http.MethodGet, "/", nil)1667 c.FileAttachment("./gin.go", newFilename)16681669 assert.Equal(t, 200, w.Code)1670 assert.Contains(t, w.Body.String(), "func New(opts ...OptionFunc) *Engine {")1671 assert.Equal(t, fmt.Sprintf("attachment; filename=\"%s\"", newFilename), w.Header().Get("Content-Disposition"))1672}16731674func TestContextRenderAndEscapeAttachment(t *testing.T) {1675 w := httptest.NewRecorder()1676 c, _ := CreateTestContext(w)1677 maliciousFilename := "tampering_field.sh\"; \\\"; dummy=.go"1678 actualEscapedResponseFilename := "tampering_field.sh\\\"; \\\\\\\"; dummy=.go"16791680 c.Request, _ = http.NewRequest(http.MethodGet, "/", nil)1681 c.FileAttachment("./gin.go", maliciousFilename)16821683 assert.Equal(t, 200, w.Code)1684 assert.Contains(t, w.Body.String(), "func New(opts ...OptionFunc) *Engine {")1685 assert.Equal(t, fmt.Sprintf("attachment; filename=\"%s\"", actualEscapedResponseFilename), w.Header().Get("Content-Disposition"))1686}16871688func TestContextRenderUTF8Attachment(t *testing.T) {1689 w := httptest.NewRecorder()1690 c, _ := CreateTestContext(w)1691 newFilename := "new🧡_filename.go"16921693 c.Request, _ = http.NewRequest(http.MethodGet, "/", nil)1694 c.FileAttachment("./gin.go", newFilename)16951696 assert.Equal(t, 200, w.Code)1697 assert.Contains(t, w.Body.String(), "func New(opts ...OptionFunc) *Engine {")1698 assert.Equal(t, `attachment; filename*=UTF-8''`+url.QueryEscape(newFilename), w.Header().Get("Content-Disposition"))1699}17001701// TestContextRenderYAML tests that the response is serialized as YAML1702// and Content-Type is set to application/yaml1703func TestContextRenderYAML(t *testing.T) {1704 w := httptest.NewRecorder()1705 c, _ := CreateTestContext(w)17061707 c.YAML(http.StatusCreated, H{"foo": "bar"})17081709 assert.Equal(t, http.StatusCreated, w.Code)1710 assert.Equal(t, "foo: bar\n", w.Body.String())1711 assert.Equal(t, "application/yaml; charset=utf-8", w.Header().Get("Content-Type"))1712}17131714// TestContextRenderTOML tests that the response is serialized as TOML1715// and Content-Type is set to application/toml1716func TestContextRenderTOML(t *testing.T) {1717 w := httptest.NewRecorder()1718 c, _ := CreateTestContext(w)17191720 c.TOML(http.StatusCreated, H{"foo": "bar"})17211722 assert.Equal(t, http.StatusCreated, w.Code)1723 assert.Equal(t, "foo = 'bar'\n", w.Body.String())1724 assert.Equal(t, "application/toml; charset=utf-8", w.Header().Get("Content-Type"))1725}17261727// TestContextRenderProtoBuf tests that the response is serialized as ProtoBuf1728// and Content-Type is set to application/x-protobuf1729// and we just use the example protobuf to check if the response is correct1730func TestContextRenderProtoBuf(t *testing.T) {1731 w := httptest.NewRecorder()1732 c, _ := CreateTestContext(w)17331734 reps := []int64{int64(1), int64(2)}1735 label := "test"1736 data := &testdata.Test{1737 Label: &label,1738 Reps: reps,1739 }17401741 c.ProtoBuf(http.StatusCreated, data)17421743 protoData, err := proto.Marshal(data)1744 require.NoError(t, err)17451746 assert.Equal(t, http.StatusCreated, w.Code)1747 assert.Equal(t, string(protoData), w.Body.String())1748 assert.Equal(t, "application/x-protobuf", w.Header().Get("Content-Type"))1749}17501751func TestContextHeaders(t *testing.T) {1752 c, _ := CreateTestContext(httptest.NewRecorder())1753 c.Header("Content-Type", "text/plain")1754 c.Header("X-Custom", "value")17551756 assert.Equal(t, "text/plain", c.Writer.Header().Get("Content-Type"))1757 assert.Equal(t, "value", c.Writer.Header().Get("X-Custom"))17581759 c.Header("Content-Type", "text/html")1760 c.Header("X-Custom", "")17611762 assert.Equal(t, "text/html", c.Writer.Header().Get("Content-Type"))1763 _, exist := c.Writer.Header()["X-Custom"]1764 assert.False(t, exist)1765}17661767// TODO1768func TestContextRenderRedirectWithRelativePath(t *testing.T) {1769 w := httptest.NewRecorder()1770 c, _ := CreateTestContext(w)17711772 c.Request, _ = http.NewRequest(http.MethodPost, "http://example.com", nil)1773 assert.Panics(t, func() { c.Redirect(299, "/new_path") })1774 assert.Panics(t, func() { c.Redirect(309, "/new_path") })17751776 c.Redirect(http.StatusMovedPermanently, "/path")1777 c.Writer.WriteHeaderNow()1778 assert.Equal(t, http.StatusMovedPermanently, w.Code)1779 assert.Equal(t, "/path", w.Header().Get("Location"))1780}17811782func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {1783 w := httptest.NewRecorder()1784 c, _ := CreateTestContext(w)17851786 c.Request, _ = http.NewRequest(http.MethodPost, "http://example.com", nil)1787 c.Redirect(http.StatusFound, "http://google.com")1788 c.Writer.WriteHeaderNow()17891790 assert.Equal(t, http.StatusFound, w.Code)1791 assert.Equal(t, "http://google.com", w.Header().Get("Location"))1792}17931794func TestContextRenderRedirectWith201(t *testing.T) {1795 w := httptest.NewRecorder()1796 c, _ := CreateTestContext(w)17971798 c.Request, _ = http.NewRequest(http.MethodPost, "http://example.com", nil)1799 c.Redirect(http.StatusCreated, "/resource")1800 c.Writer.WriteHeaderNow()18011802 assert.Equal(t, http.StatusCreated, w.Code)1803 assert.Equal(t, "/resource", w.Header().Get("Location"))1804}18051806func TestContextRenderRedirectAll(t *testing.T) {1807 c, _ := CreateTestContext(httptest.NewRecorder())1808 c.Request, _ = http.NewRequest(http.MethodPost, "http://example.com", nil)1809 assert.Panics(t, func() { c.Redirect(http.StatusOK, "/resource") })1810 assert.Panics(t, func() { c.Redirect(http.StatusAccepted, "/resource") })1811 assert.Panics(t, func() { c.Redirect(299, "/resource") })1812 assert.Panics(t, func() { c.Redirect(309, "/resource") })1813 assert.NotPanics(t, func() { c.Redirect(http.StatusMultipleChoices, "/resource") })1814 assert.NotPanics(t, func() { c.Redirect(http.StatusPermanentRedirect, "/resource") })1815}18161817func TestContextNegotiationWithJSON(t *testing.T) {1818 w := httptest.NewRecorder()1819 c, _ := CreateTestContext(w)1820 c.Request, _ = http.NewRequest(http.MethodPost, "", nil)18211822 c.Negotiate(http.StatusOK, Negotiate{1823 Offered: []string{MIMEJSON, MIMEXML, MIMEYAML, MIMEYAML2},1824 Data: H{"foo": "bar"},1825 })18261827 assert.Equal(t, http.StatusOK, w.Code)1828 assert.JSONEq(t, `{"foo":"bar"}`, w.Body.String())1829 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))1830}18311832func TestContextNegotiationWithXML(t *testing.T) {1833 w := httptest.NewRecorder()1834 c, _ := CreateTestContext(w)1835 c.Request, _ = http.NewRequest(http.MethodPost, "", nil)18361837 c.Negotiate(http.StatusOK, Negotiate{1838 Offered: []string{MIMEXML, MIMEJSON, MIMEYAML, MIMEYAML2},1839 Data: H{"foo": "bar"},1840 })18411842 assert.Equal(t, http.StatusOK, w.Code)1843 assert.Equal(t, "<map><foo>bar</foo></map>", w.Body.String())1844 assert.Equal(t, "application/xml; charset=utf-8", w.Header().Get("Content-Type"))1845}18461847func TestContextNegotiationWithYAML(t *testing.T) {1848 w := httptest.NewRecorder()1849 c, _ := CreateTestContext(w)1850 c.Request, _ = http.NewRequest(http.MethodPost, "", nil)18511852 c.Negotiate(http.StatusOK, Negotiate{1853 Offered: []string{MIMEYAML, MIMEXML, MIMEJSON, MIMETOML, MIMEYAML2},1854 Data: H{"foo": "bar"},1855 })18561857 assert.Equal(t, http.StatusOK, w.Code)1858 assert.Equal(t, "foo: bar\n", w.Body.String())1859 assert.Equal(t, "application/yaml; charset=utf-8", w.Header().Get("Content-Type"))1860}18611862func TestContextNegotiationWithTOML(t *testing.T) {1863 w := httptest.NewRecorder()1864 c, _ := CreateTestContext(w)1865 c.Request, _ = http.NewRequest(http.MethodPost, "", nil)18661867 c.Negotiate(http.StatusOK, Negotiate{1868 Offered: []string{MIMETOML, MIMEXML, MIMEJSON, MIMEYAML, MIMEYAML2},1869 Data: H{"foo": "bar"},1870 })18711872 assert.Equal(t, http.StatusOK, w.Code)1873 assert.Equal(t, "foo = 'bar'\n", w.Body.String())1874 assert.Equal(t, "application/toml; charset=utf-8", w.Header().Get("Content-Type"))1875}18761877func TestContextNegotiationWithHTML(t *testing.T) {1878 w := httptest.NewRecorder()1879 c, router := CreateTestContext(w)1880 c.Request, _ = http.NewRequest(http.MethodPost, "", nil)1881 templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))1882 router.SetHTMLTemplate(templ)18831884 c.Negotiate(http.StatusOK, Negotiate{1885 Offered: []string{MIMEHTML},1886 Data: H{"name": "gin"},1887 HTMLName: "t",1888 })18891890 assert.Equal(t, http.StatusOK, w.Code)1891 assert.Equal(t, "Hello gin", w.Body.String())1892 assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))1893}18941895func TestContextNegotiationWithPROTOBUF(t *testing.T) {1896 w := httptest.NewRecorder()1897 c, _ := CreateTestContext(w)1898 c.Request = httptest.NewRequest(http.MethodPost, "/", nil)18991900 reps := []int64{int64(1), int64(2)}1901 label := "test"1902 data := &testdata.Test{1903 Label: &label,1904 Reps: reps,1905 }19061907 c.Negotiate(http.StatusCreated, Negotiate{1908 Offered: []string{MIMEPROTOBUF, MIMEJSON, MIMEXML},1909 Data: data,1910 })19111912 // Marshal original data for comparison1913 protoData, err := proto.Marshal(data)1914 require.NoError(t, err)19151916 assert.Equal(t, http.StatusCreated, w.Code)1917 assert.Equal(t, string(protoData), w.Body.String())1918 assert.Equal(t, "application/x-protobuf", w.Header().Get("Content-Type"))1919}19201921func TestContextNegotiationWithBSON(t *testing.T) {1922 w := httptest.NewRecorder()1923 c, _ := CreateTestContext(w)1924 c.Request, _ = http.NewRequest(http.MethodPost, "", nil)19251926 c.Negotiate(http.StatusOK, Negotiate{1927 Offered: []string{MIMEBSON, MIMEXML, MIMEJSON, MIMEYAML, MIMEYAML2},1928 Data: H{"foo": "bar"},1929 })19301931 bData, _ := bson.Marshal(H{"foo": "bar"})19321933 assert.Equal(t, http.StatusOK, w.Code)1934 assert.Equal(t, string(bData), w.Body.String())1935 assert.Equal(t, "application/bson", w.Header().Get("Content-Type"))1936}19371938func TestContextNegotiationNotSupport(t *testing.T) {1939 w := httptest.NewRecorder()1940 c, _ := CreateTestContext(w)1941 c.Request, _ = http.NewRequest(http.MethodPost, "", nil)19421943 c.Negotiate(http.StatusOK, Negotiate{1944 Offered: []string{MIMEPOSTForm},1945 })19461947 assert.Equal(t, http.StatusNotAcceptable, w.Code)1948 assert.Equal(t, abortIndex, c.index)1949 assert.True(t, c.IsAborted())1950}19511952func TestContextNegotiationFormat(t *testing.T) {1953 c, _ := CreateTestContext(httptest.NewRecorder())1954 c.Request, _ = http.NewRequest(http.MethodPost, "", nil)19551956 assert.Panics(t, func() { c.NegotiateFormat() })1957 assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON, MIMEXML)) //nolint:testifylint1958 assert.Equal(t, MIMEHTML, c.NegotiateFormat(MIMEHTML, MIMEJSON))1959}19601961func TestContextNegotiationFormatWithAccept(t *testing.T) {1962 c, _ := CreateTestContext(httptest.NewRecorder())1963 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)1964 c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9;q=0.8")19651966 assert.Equal(t, MIMEXML, c.NegotiateFormat(MIMEJSON, MIMEXML))1967 assert.Equal(t, MIMEHTML, c.NegotiateFormat(MIMEXML, MIMEHTML))1968 assert.Empty(t, c.NegotiateFormat(MIMEJSON))1969}19701971func TestContextNegotiationFormatWithWildcardAccept(t *testing.T) {1972 c, _ := CreateTestContext(httptest.NewRecorder())1973 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)1974 c.Request.Header.Add("Accept", "*/*")19751976 assert.Equal(t, "*/*", c.NegotiateFormat("*/*"))1977 assert.Equal(t, "text/*", c.NegotiateFormat("text/*"))1978 assert.Equal(t, "application/*", c.NegotiateFormat("application/*"))1979 assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON)) //nolint:testifylint1980 assert.Equal(t, MIMEXML, c.NegotiateFormat(MIMEXML))1981 assert.Equal(t, MIMEHTML, c.NegotiateFormat(MIMEHTML))19821983 c, _ = CreateTestContext(httptest.NewRecorder())1984 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)1985 c.Request.Header.Add("Accept", "text/*")19861987 assert.Equal(t, "*/*", c.NegotiateFormat("*/*"))1988 assert.Equal(t, "text/*", c.NegotiateFormat("text/*"))1989 assert.Empty(t, c.NegotiateFormat("application/*"))1990 assert.Empty(t, c.NegotiateFormat(MIMEJSON))1991 assert.Empty(t, c.NegotiateFormat(MIMEXML))1992 assert.Equal(t, MIMEHTML, c.NegotiateFormat(MIMEHTML))1993}19941995func TestContextNegotiationFormatCustom(t *testing.T) {1996 c, _ := CreateTestContext(httptest.NewRecorder())1997 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)1998 c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9;q=0.8")19992000 c.Accepted = nilThe first 2,000 of 4,057 lines.