Skip to content
Myr

ci(golangci-lint): update configuration and fix lint issues (#4247)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* ci: update golangci-lint configuration and lint settings - Update golangci-lint to version 2 - Enable new linters and adjust existing ones - Update lint settings across multiple test files - Remove unused struct and variable checks - Add new lint exclusions for generated code and specific directories Signed-off-by: Flc <four_leaf_clover@foxmail.com> * ci(github): update golangci-lint-action to v8 and lint version to v2.3.4 Signed-off-by: Flc <four_leaf_clover@foxmail.com> * ci: downgrade golangci-lint to v2.1.6 Signed-off-by: Flc <four_leaf_clover@foxmail.com> * ci(golangci): add gofumpt linter and fix related issues- Added gofumpt linter to .golangci.yml Signed-off-by: Flc <four_leaf_clover@foxmail.com> * test: ignore testifylint and gofumpt lints in specific test cases Signed-off-by: Flc <four_leaf_clover@foxmail.com> * build(deps): remove golang.org/x/lint - Remove golang.org/x/lint package from go.mod - Update related dependencies in go.sum Signed-off-by: flc1125 <four_leaf_clover@foxmail.com> * build(deps): downgrade golang.org/x/mod and golang.org/x/tools - Downgrade golang.org/x/mod from v0.24.0 to v0.18.0 - Downgrade golang.org/x/tools from v0.33.0 to v.22.0 These changes are made to address compatibility issues with the current project setup. Signed-off-by: flc1125 <four_leaf_clover@foxmail.com> ---------

authored by Flc゛ · committed by GitHub · parent 8fb3136 · Browse files · 27 files+164 added−149 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Signed-off-by: Flc <four_leaf_clover@foxmail.com>
  • Signed-off-by: flc1125 <four_leaf_clover@foxmail.com>

Diff stats

27 files+164 added−149 removed

  • other:+164 added−149 removed

27 files+164 added−149 removed

modified:.github/workflows/gin.yml+2 added-2 removed
modified:binding/binding_test.go+2 added-4 removed
49 unmodified lines
5051type FooBarFileFailStruct struct {52 FooBarStruct53 File *multipart.FileHeader `invalid_name:"file" binding:"required"`54 // for unexport test55 data *multipart.FileHeader `form:"data" binding:"required"`54}5556type FooDefaultBarStruct struct {57 FooStruct
1002 unmodified lines
1060 req.Header.Add("Content-Type", MIMEPOSTForm)1061 }1062 err := b.Bind(req, &obj)1063 require.NoError(t, err)1066 assert.Equal(t, "", obj.TestName)1064 assert.Empty(t, obj.TestName)10651066 obj = InvalidNameType{}1067 req = requestWithBody(method, badPath, badBody)1068 err = JSON.Bind(req, &obj)
246 unmodified lines
1315 obj := FooStruct{}1316 req := requestWithBody(http.MethodPost, path, body)1317 err := b.Bind(req, &obj)1318 require.Error(t, err)1321 assert.Equal(t, "", obj.Foo)1319 assert.Empty(t, obj.Foo)13201321 obj = FooStruct{}1322 req = requestWithBody(http.MethodPost, badPath, badBody)1323 err = JSON.Bind(req, &obj)
95 unmodified lines
modified:binding/default_validator_test.go+4 added-2 removed
16 unmodified lines
17 }{18 {"has nil elements", SliceValidationError{errors.New("test error"), nil}, "[0]: test error"},19 {"has zero elements", SliceValidationError{}, ""},20 {"has one element", SliceValidationError{errors.New("test one error")}, "[0]: test one error"},21 {21 {"has two elements",22 "has two elements",23 SliceValidationError{24 errors.New("first error"),25 errors.New("second error"),26 },27 "[0]: first error\n[1]: second error",28 },29 {28 {"has many elements",30 "has many elements",31 SliceValidationError{32 errors.New("first error"),33 errors.New("second error"),34 nil,
56 unmodified lines
modified:binding/form_mapping_test.go+18 added-18 removed
507 unmodified lines
508 }509 err := mappingByPtr(&s, formSource{"data": {`file:/foo:happiness`}}, "form")510 require.NoError(t, err)511512 assert.EqualValues(t, "file", s.FileData.Protocol)513 assert.EqualValues(t, "/foo", s.FileData.Path)514 assert.EqualValues(t, "happiness", s.FileData.Name)512 assert.Equal(t, "file", s.FileData.Protocol)513 assert.Equal(t, "/foo", s.FileData.Path)514 assert.Equal(t, "happiness", s.FileData.Name)515}516517func TestMappingCustomStructTypeWithURITag(t *testing.T) {518 var s struct {
1 unmodified line
520 }521 err := mappingByPtr(&s, formSource{"data": {`file:/foo:happiness`}}, "uri")522 require.NoError(t, err)523524 assert.EqualValues(t, "file", s.FileData.Protocol)525 assert.EqualValues(t, "/foo", s.FileData.Path)526 assert.EqualValues(t, "happiness", s.FileData.Name)524 assert.Equal(t, "file", s.FileData.Protocol)525 assert.Equal(t, "/foo", s.FileData.Path)526 assert.Equal(t, "happiness", s.FileData.Name)527}528529func TestMappingCustomPointerStructTypeWithFormTag(t *testing.T) {530 var s struct {
1 unmodified line
532 }533 err := mappingByPtr(&s, formSource{"data": {`file:/foo:happiness`}}, "form")534 require.NoError(t, err)535536 assert.EqualValues(t, "file", s.FileData.Protocol)537 assert.EqualValues(t, "/foo", s.FileData.Path)538 assert.EqualValues(t, "happiness", s.FileData.Name)536 assert.Equal(t, "file", s.FileData.Protocol)537 assert.Equal(t, "/foo", s.FileData.Path)538 assert.Equal(t, "happiness", s.FileData.Name)539}540541func TestMappingCustomPointerStructTypeWithURITag(t *testing.T) {542 var s struct {
1 unmodified line
544 }545 err := mappingByPtr(&s, formSource{"data": {`file:/foo:happiness`}}, "uri")546 require.NoError(t, err)547548 assert.EqualValues(t, "file", s.FileData.Protocol)549 assert.EqualValues(t, "/foo", s.FileData.Path)550 assert.EqualValues(t, "happiness", s.FileData.Name)548 assert.Equal(t, "file", s.FileData.Protocol)549 assert.Equal(t, "/foo", s.FileData.Path)550 assert.Equal(t, "happiness", s.FileData.Name)551}552553type customPath []string554
14 unmodified lines
569 }570 err := mappingByPtr(&s, formSource{"path": {`bar/foo`}}, "uri")571 require.NoError(t, err)572573 assert.EqualValues(t, "bar", s.FileData[0])574 assert.EqualValues(t, "foo", s.FileData[1])573 assert.Equal(t, "bar", s.FileData[0])574 assert.Equal(t, "foo", s.FileData[1])575}576577func TestMappingCustomSliceForm(t *testing.T) {578 var s struct {
1 unmodified line
580 }581 err := mappingByPtr(&s, formSource{"path": {`bar/foo`}}, "form")582 require.NoError(t, err)583584 assert.EqualValues(t, "bar", s.FileData[0])585 assert.EqualValues(t, "foo", s.FileData[1])584 assert.Equal(t, "bar", s.FileData[0])585 assert.Equal(t, "foo", s.FileData[1])586}587588type objectID [12]byte589
30 unmodified lines
620 err := mappingByPtr(&s, formSource{"id": {val}}, "uri")621 require.NoError(t, err)622623 expected, _ := convertTo(val)624 assert.EqualValues(t, expected, s.FileData)624 assert.Equal(t, expected, s.FileData)625}626627func TestMappingCustomArrayForm(t *testing.T) {628 var s struct {
3 unmodified lines
632 err := mappingByPtr(&s, formSource{"id": {val}}, "form")633 require.NoError(t, err)634635 expected, _ := convertTo(val)636 assert.EqualValues(t, expected, s.FileData)636 assert.Equal(t, expected, s.FileData)637}
modified:binding/form.go+5 added-3 removed
9 unmodified lines
10)1112const defaultMemory = 32 << 201314type formBinding struct{}15type formPostBinding struct{}16type formMultipartBinding struct{}14type (15 formBinding struct{}16 formPostBinding struct{}17 formMultipartBinding struct{}18)1920func (formBinding) Name() string {21 return "form"22}
42 unmodified lines
modified:binding/header.go-1 removed
15 unmodified lines
16 return "header"17}1819func (headerBinding) Bind(req *http.Request, obj any) error {2020 if err := mapHeader(obj, req.Header); err != nil {21 return err22 }23
14 unmodified lines
modified:binding/validate_test.go+7 added-7 removed
156 unmodified lines
157 StructMap *mapNoValidationSub158}159160func TestValidateNoValidationPointers(t *testing.T) {161 //origin := createNoValidation_values()162 //test := createNoValidation_values()161 // origin := createNoValidation_values()162 // test := createNoValidation_values()163 empty := structNoValidationPointer{}164165 //assert.Nil(t, validate(test))166 //assert.Nil(t, validate(&test))165 // assert.Nil(t, validate(test))166 // assert.Nil(t, validate(&test))167 require.NoError(t, validate(empty))168 require.NoError(t, validate(&empty))169170 //assert.Equal(t, origin, test)170 // assert.Equal(t, origin, test)171}172173type Object map[string]any174
22 unmodified lines
197 Integer int198}199200func toZero(sl validator.StructLevel) {201 var s *structModifyValidation = sl.Top().Interface().(*structModifyValidation)201 s := sl.Top().Interface().(*structModifyValidation)202 s.Integer = 0203}204205func TestValidateAndModifyStruct(t *testing.T) {
42 unmodified lines
248249 // Check that we got back non-nil errs250 require.Error(t, errs)251 // Check that the error matches expectation252 require.Error(t, errs, "", "", "notone")252 require.Error(t, errs, "notone")253}
modified:binding/xml.go+1 added
22 unmodified lines
2324func (xmlBinding) BindBody(body []byte, obj any) error {25 return decodeXML(bytes.NewReader(body), obj)26}2728func decodeXML(r io.Reader, obj any) error {29 decoder := xml.NewDecoder(r)30 if err := decoder.Decode(obj); err != nil {31 return err
3 unmodified lines
modified:ginS/gins.go+4 added-2 removed
10 unmodified lines
1112 "github.com/gin-gonic/gin"13)1415var (15var once sync.Once16var internalEngine *gin.Engine16 once sync.Once17 internalEngine *gin.Engine18)1920func engine() *gin.Engine {21 once.Do(func() {22 internalEngine = gin.Default()
145 unmodified lines
modified:internal/bytesconv/bytesconv_test.go+4 added-2 removed
10 unmodified lines
11 "testing"12 "time"13)1415var (15var testString = "Albert Einstein: Logic will get you from A to B. Imagination will take you everywhere."16var testBytes = []byte(testString)16 testString = "Albert Einstein: Logic will get you from A to B. Imagination will take you everywhere."17 testBytes = []byte(testString)18)1920func rawBytesToStr(b []byte) string {21 return string(b)22}
79 unmodified lines
modified:internal/fs/fs.go-1 removed
11 unmodified lines
1213// Open passes `Open` to the upstream implementation and return an [fs.File].14func (o FileSystem) Open(name string) (fs.File, error) {15 f, err := o.FileSystem.Open(name)1616 if err != nil {17 return nil, err18 }19
2 unmodified lines
modified:render/html.go+1 added
65 unmodified lines
66 Name: name,67 Data: data,68 }69}7071func (r HTMLDebug) loadTemplate() *template.Template {72 if r.FuncMap == nil {73 r.FuncMap = template.FuncMap{}74 }
27 unmodified lines
modified:render/render_test.go+6 added-6 removed
36 unmodified lines
3738 err := (JSON{data}).Render(w)3940 require.NoError(t, err)41 assert.Equal(t, "{\"foo\":\"bar\",\"html\":\"\\u003cb\\u003e\"}", w.Body.String())41 assert.JSONEq(t, "{\"foo\":\"bar\",\"html\":\"\\u003cb\\u003e\"}", w.Body.String())42 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))43}4445func TestRenderJSONError(t *testing.T) {
13 unmodified lines
5960 err := (IndentedJSON{data}).Render(w)6162 require.NoError(t, err)63 assert.Equal(t, "{\n \"bar\": \"foo\",\n \"foo\": \"bar\"\n}", w.Body.String())63 assert.JSONEq(t, "{\n \"bar\": \"foo\",\n \"foo\": \"bar\"\n}", w.Body.String())64 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))65}6667func TestRenderIndentedJSONPanics(t *testing.T) {
16 unmodified lines
8485 err1 := (SecureJSON{"while(1);", data}).Render(w1)8687 require.NoError(t, err1)88 assert.Equal(t, "{\"foo\":\"bar\"}", w1.Body.String())88 assert.JSONEq(t, "{\"foo\":\"bar\"}", w1.Body.String())89 assert.Equal(t, "application/json; charset=utf-8", w1.Header().Get("Content-Type"))9091 w2 := httptest.NewRecorder()92 datas := []map[string]any{{
100 unmodified lines
193194 e := (JsonpJSON{"", data}).Render(w)195 require.NoError(t, e)196197 assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())197 assert.JSONEq(t, "{\"foo\":\"bar\"}", w.Body.String())198 assert.Equal(t, "application/javascript; charset=utf-8", w.Header().Get("Content-Type"))199}200201func TestRenderJsonpJSONFail(t *testing.T) {
14 unmodified lines
216217 err := (AsciiJSON{data1}).Render(w1)218219 require.NoError(t, err)220 assert.Equal(t, "{\"lang\":\"GO\\u8bed\\u8a00\",\"tag\":\"\\u003cbr\\u003e\"}", w1.Body.String())220 assert.JSONEq(t, "{\"lang\":\"GO\\u8bed\\u8a00\",\"tag\":\"\\u003cbr\\u003e\"}", w1.Body.String())221 assert.Equal(t, "application/json", w1.Header().Get("Content-Type"))222223 w2 := httptest.NewRecorder()224 data2 := 3.1415926
18 unmodified lines
243 "html": "<b>",244 }245 err := (PureJSON{data}).Render(w)246 require.NoError(t, err)247 assert.Equal(t, "{\"foo\":\"bar\",\"html\":\"<b>\"}\n", w.Body.String())247 assert.JSONEq(t, "{\"foo\":\"bar\",\"html\":\"<b>\"}\n", w.Body.String())248 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))249}250251type xmlmap map[string]any
370 unmodified lines
modified:.golangci.yml+65 added-55 removed
1run:2 timeout: 5m1version: "2"2linters:3 enable:4 - asciicheck5 - copyloopvar6 - dogsled7 - durationcheck8 - errcheck8 - errorlint10 - copyloopvar11 - gci12 - gofmt13 - goimports9 - gosec10 - misspell11 - nakedret12 - nilerr
2 unmodified lines
15 - revive16 - testifylint17 - usestdlibvars18 - wastedassign2425linters-settings:26 gosec:27 # To select a subset of rules to run.28 # Available rules: https://github.com/securego/gosec#available-rules29 # Default: [] - means include all rules30 includes:31 - G10232 - G10633 - G10834 - G10935 - G11136 - G11237 - G20138 - G20339 perfsprint:40 err-error: true41 errorf: true42 int-conversion: true43 sprintf1: true44 strconcat: true45 testifylint:46 enable-all: true4748issues:49 exclude-rules:50 - linters:51 - structcheck52 - unused53 text: "`data` is unused"54 - linters:55 - staticcheck56 text: "SA1019:"57 - linters:58 - revive59 text: "var-naming:"60 - linters:61 - revive62 text: "exported:"63 - path: _test\.go64 linters:65 - gosec # security is not make sense in tests66 - linters:67 - revive68 path: _test\.go69 - path: gin.go70 linters:71 - gci19 settings:20 gosec:21 includes:22 - G10223 - G10624 - G10825 - G10926 - G11127 - G11228 - G20129 - G20330 perfsprint:31 int-conversion: true32 err-error: true33 errorf: true34 sprintf1: true35 strconcat: true36 testifylint:37 enable-all: true38 exclusions:39 generated: lax40 presets:41 - comments42 - common-false-positives43 - legacy44 - std-error-handling45 rules:46 - linters:47 - structcheck48 - unused49 text: '`data` is unused'50 - linters:51 - staticcheck52 text: 'SA1019:'53 - linters:54 - revive55 text: 'var-naming:'56 - linters:57 - revive58 text: 'exported:'59 - linters:60 - gosec61 path: _test\.go62 - linters:63 - revive64 path: _test\.go65 paths:66 - third_party$67 - builtin$68 - examples$69formatters:70 enable:71 - gci72 - gofmt73 - gofumpt74 - goimports75 exclusions:76 generated: lax77 paths:78 - third_party$79 - builtin$80 - examples$81 - gin.go
modified:context_test.go+19 added-19 removed
916 unmodified lines
917918 c.JSON(http.StatusCreated, H{"foo": "bar", "html": "<b>"})919920 assert.Equal(t, http.StatusCreated, w.Code)921 assert.Equal(t, "{\"foo\":\"bar\",\"html\":\"\\u003cb\\u003e\"}", w.Body.String())921 assert.JSONEq(t, "{\"foo\":\"bar\",\"html\":\"\\u003cb\\u003e\"}", w.Body.String())922 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))923}924925// Tests that the response is serialized as JSONP
19 unmodified lines
945946 c.JSONP(http.StatusCreated, H{"foo": "bar"})947948 assert.Equal(t, http.StatusCreated, w.Code)949 assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())949 assert.JSONEq(t, "{\"foo\":\"bar\"}", w.Body.String())950 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))951}952953// Tests that no JSON is rendered if code is 204
17 unmodified lines
971 c.Header("Content-Type", "application/vnd.api+json")972 c.JSON(http.StatusCreated, H{"foo": "bar"})973974 assert.Equal(t, http.StatusCreated, w.Code)975 assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())975 assert.JSONEq(t, "{\"foo\":\"bar\"}", w.Body.String())976 assert.Equal(t, "application/vnd.api+json", w.Header().Get("Content-Type"))977}978979// Tests that no Custom JSON is rendered if code is 204
17 unmodified lines
997998 c.IndentedJSON(http.StatusCreated, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})9991000 assert.Equal(t, http.StatusCreated, w.Code)1001 assert.Equal(t, "{\n \"bar\": \"foo\",\n \"foo\": \"bar\",\n \"nested\": {\n \"foo\": \"bar\"\n }\n}", w.Body.String())1001 assert.JSONEq(t, "{\n \"bar\": \"foo\",\n \"foo\": \"bar\",\n \"nested\": {\n \"foo\": \"bar\"\n }\n}", w.Body.String())1002 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))1003}10041005// Tests that no Custom JSON is rendered if code is 204
52 unmodified lines
1058 w := httptest.NewRecorder()1059 c, _ := CreateTestContext(w)1060 c.PureJSON(http.StatusCreated, H{"foo": "bar", "html": "<b>"})1061 assert.Equal(t, http.StatusCreated, w.Code)1062 assert.Equal(t, "{\"foo\":\"bar\",\"html\":\"<b>\"}\n", w.Body.String())1062 assert.JSONEq(t, "{\"foo\":\"bar\",\"html\":\"<b>\"}\n", w.Body.String())1063 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))1064}10651066// Tests that the response executes the templates
165 unmodified lines
1232 "foo": "bar",1233 "bar": "foo",1234 })12351236 assert.Equal(t, strings.Replace(w.Body.String(), " ", "", -1), strings.Replace("event:float\ndata:1.5\n\nid:123\ndata:text\n\nevent:chat\ndata:{\"bar\":\"foo\",\"foo\":\"bar\"}\n\n", " ", "", -1))1236 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", " ", ""))1237}12381239func TestContextRenderFile(t *testing.T) {1240 w := httptest.NewRecorder()
5 unmodified lines
1246 assert.Equal(t, http.StatusOK, w.Code)1247 assert.Contains(t, w.Body.String(), "func New(opts ...OptionFunc) *Engine {")1248 // Content-Type='text/plain; charset=utf-8' when go version <= 1.16,1249 // else, Content-Type='text/x-go; charset=utf-8'1250 assert.NotEqual(t, "", w.Header().Get("Content-Type"))1250 assert.NotEmpty(t, w.Header().Get("Content-Type"))1251}12521253func TestContextRenderFileFromFS(t *testing.T) {1254 w := httptest.NewRecorder()
5 unmodified lines
1260 assert.Equal(t, http.StatusOK, w.Code)1261 assert.Contains(t, w.Body.String(), "func New(opts ...OptionFunc) *Engine {")1262 // Content-Type='text/plain; charset=utf-8' when go version <= 1.16,1263 // else, Content-Type='text/x-go; charset=utf-8'1264 assert.NotEqual(t, "", w.Header().Get("Content-Type"))1264 assert.NotEmpty(t, w.Header().Get("Content-Type"))1265 assert.Equal(t, "/some/path", c.Request.URL.Path)1266}12671268func TestContextRenderAttachment(t *testing.T) {
162 unmodified lines
1431 Data: H{"foo": "bar"},1432 })14331434 assert.Equal(t, http.StatusOK, w.Code)1435 assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())1435 assert.JSONEq(t, "{\"foo\":\"bar\"}", w.Body.String())1436 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))1437}14381439func TestContextNegotiationWithXML(t *testing.T) {
77 unmodified lines
1517 c, _ := CreateTestContext(httptest.NewRecorder())1518 c.Request, _ = http.NewRequest(http.MethodPost, "", nil)15191520 assert.Panics(t, func() { c.NegotiateFormat() })1521 assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON, MIMEXML))1521 assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON, MIMEXML)) //nolint:testifylint1522 assert.Equal(t, MIMEHTML, c.NegotiateFormat(MIMEHTML, MIMEJSON))1523}15241525func TestContextNegotiationFormatWithAccept(t *testing.T) {
13 unmodified lines
15391540 assert.Equal(t, "*/*", c.NegotiateFormat("*/*"))1541 assert.Equal(t, "text/*", c.NegotiateFormat("text/*"))1542 assert.Equal(t, "application/*", c.NegotiateFormat("application/*"))1543 assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON))1543 assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON)) //nolint:testifylint1544 assert.Equal(t, MIMEXML, c.NegotiateFormat(MIMEXML))1545 assert.Equal(t, MIMEHTML, c.NegotiateFormat(MIMEHTML))15461547 c, _ = CreateTestContext(httptest.NewRecorder())
1 unmodified line
1549 c.Request.Header.Add("Accept", "text/*")15501551 assert.Equal(t, "*/*", c.NegotiateFormat("*/*"))1552 assert.Equal(t, "text/*", c.NegotiateFormat("text/*"))1553 assert.Equal(t, "", c.NegotiateFormat("application/*"))1554 assert.Equal(t, "", c.NegotiateFormat(MIMEJSON))1555 assert.Equal(t, "", c.NegotiateFormat(MIMEXML))1553 assert.Empty(t, c.NegotiateFormat("application/*"))1554 assert.Empty(t, c.NegotiateFormat(MIMEJSON))1555 assert.Empty(t, c.NegotiateFormat(MIMEXML))1556 assert.Equal(t, MIMEHTML, c.NegotiateFormat(MIMEHTML))1557}15581559func TestContextNegotiationFormatCustom(t *testing.T) {
3 unmodified lines
15631564 c.Accepted = nil1565 c.SetAccepted(MIMEJSON, MIMEXML)15661567 assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON, MIMEXML))1567 assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON, MIMEXML)) //nolint:testifylint1568 assert.Equal(t, MIMEXML, c.NegotiateFormat(MIMEXML, MIMEHTML))1569 assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON))1569 assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON)) //nolint:testifylint1570}15711572func TestContextNegotiationFormat2(t *testing.T) {1573 c, _ := CreateTestContext(httptest.NewRecorder())1574 c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)1575 c.Request.Header.Add("Accept", "image/tiff-fx")15761577 assert.Equal(t, "", c.NegotiateFormat("image/tiff"))1577 assert.Empty(t, c.NegotiateFormat("image/tiff"))1578}15791580func TestContextIsAborted(t *testing.T) {1581 c, _ := CreateTestContext(httptest.NewRecorder())
51 unmodified lines
1633 buf := new(bytes.Buffer)1634 _, err := buf.ReadFrom(w.Body)1635 require.NoError(t, err)1636 jsonStringBody := buf.String()1637 assert.Equal(t, "{\"foo\":\"fooValue\",\"bar\":\"barValue\"}", jsonStringBody)1637 assert.JSONEq(t, "{\"foo\":\"fooValue\",\"bar\":\"barValue\"}", jsonStringBody)1638}16391640func TestContextError(t *testing.T) {1641 c, _ := CreateTestContext(httptest.NewRecorder())
1433 unmodified lines
3075 // Result() has headers frozen when WriteHeaderNow() has been called3076 // Compared to this time, this is when the response headers will be flushed3077 // As response is flushed on c.String, the Header cannot be set by the first3078 // middleware. Assert this3079 assert.Equal(t, "", w.Result().Header.Get("X-Test"))3079 assert.Empty(t, w.Result().Header.Get("X-Test"))3080 assert.Equal(t, "present", w.Result().Header.Get("X-Test-2"))3081}30823083func TestContextNext(t *testing.T) {
168 unmodified lines
modified:errors_test.go+3 added-3 removed
32 unmodified lines
33 "meta": "some data",34 }, err.JSON())3536 jsonBytes, _ := json.Marshal(err)37 assert.Equal(t, "{\"error\":\"test error\",\"meta\":\"some data\"}", string(jsonBytes))37 assert.JSONEq(t, "{\"error\":\"test error\",\"meta\":\"some data\"}", string(jsonBytes))3839 err.SetMeta(H{ //nolint: errcheck40 "status": "200",41 "data": "some data",
50 unmodified lines
92 H{"error": "second", "meta": "some data"},93 H{"error": "third", "status": "400"},94 }, errs.JSON())95 jsonBytes, _ := json.Marshal(errs)96 assert.Equal(t, "[{\"error\":\"first\"},{\"error\":\"second\",\"meta\":\"some data\"},{\"error\":\"third\",\"status\":\"400\"}]", string(jsonBytes))96 assert.JSONEq(t, "[{\"error\":\"first\"},{\"error\":\"second\",\"meta\":\"some data\"},{\"error\":\"third\",\"status\":\"400\"}]", string(jsonBytes))97 errs = errorMsgs{98 {Err: errors.New("first"), Type: ErrorTypePrivate},99 }100 assert.Equal(t, H{"error": "first"}, errs.JSON())101 jsonBytes, _ = json.Marshal(errs)102 assert.Equal(t, "{\"error\":\"first\"}", string(jsonBytes))102 assert.JSONEq(t, "{\"error\":\"first\"}", string(jsonBytes))103104 errs = errorMsgs{}105 assert.Nil(t, errs.Last())106 assert.Nil(t, errs.JSON())
34 unmodified lines
modified:fs.go-1 removed
15 unmodified lines
1617// Open passes `Open` to the upstream implementation without `Readdir` functionality.18func (o OnlyFilesFS) Open(name string) (http.File, error) {19 f, err := o.FileSystem.Open(name)2020 if err != nil {21 return nil, err22 }23
27 unmodified lines
modified:gin_integration_test.go+3 added-4 removed
26 unmodified lines
27// params[0]=url example:http://127.0.0.1:8080/index (cannot be empty)28// params[1]=response status (custom compare status) default:"200 OK"29// params[2]=response body (custom compare content) default:"it worked"30func testRequest(t *testing.T, params ...string) {3131 if len(params) == 0 {32 t.Fatal("url cannot be empty")33 }34
10 unmodified lines
4546 body, ioerr := io.ReadAll(resp.Body)47 require.NoError(t, ioerr)4850 var responseStatus = "200 OK"49 responseStatus := "200 OK"50 if len(params) > 1 && params[1] != "" {51 responseStatus = params[1]52 }5355 var responseBody = "it worked"54 responseBody := "it worked"55 if len(params) > 2 && params[2] != "" {56 responseBody = params[2]57 }58
109 unmodified lines
168 testRequest(t, "https://localhost:8443/example")169}170171func TestPusher(t *testing.T) {173 var html = template.Must(template.New("https").Parse(`172 html := template.Must(template.New("https").Parse(`173<html>174<head>175 <title>Https Test</title>176 <script src="/assets/app.js"></script>
424 unmodified lines
modified:gin_test.go+2 added-2 removed
44 unmodified lines
45 c.HTML(http.StatusOK, "hello.tmpl", map[string]string{"name": "world"})46 })47 router.GET("/raw", func(c *Context) {48 c.HTML(http.StatusOK, "raw.tmpl", map[string]any{49 "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),49 "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC), //nolint:gofumpt50 })51 })52 })53
828 unmodified lines
882883type Birthday string884885func (b *Birthday) UnmarshalParam(param string) error {886 *b = Birthday(strings.Replace(param, "-", "/", -1))886 *b = Birthday(strings.ReplaceAll(param, "-", "/"))887 return nil888}889890func TestCustomUnmarshalStruct(t *testing.T) {
25 unmodified lines
modified:gin.go+1 added-2 removed
16 unmodified lines
1718 "github.com/gin-gonic/gin/internal/bytesconv"19 filesystem "github.com/gin-gonic/gin/internal/fs"20 "github.com/gin-gonic/gin/render"2121 "github.com/quic-go/quic-go/http3"22 "golang.org/x/net/http2"23 "golang.org/x/net/http2/h2c"24)
189 unmodified lines
214 secureJSONPrefix: "while(1);",215 trustedProxies: []string{"0.0.0.0/0", "::/0"},216 trustedCIDRs: defaultTrustedCIDRs,217 }219 engine.RouterGroup.engine = engine218 engine.engine = engine219 engine.pool.New = func() any {220 return engine.allocateContext(engine.maxParams)221 }222 return engine.With(opts...)
566 unmodified lines
modified:githubapi_test.go+4 added-4 removed
296 unmodified lines
297 }298 router.Handle(http.MethodGet, "/rest/:name/:id", func(c *Context) {299 var person Person300 require.NoError(t, c.ShouldBindUri(&person))301 assert.NotEqual(t, "", person.Name)302 assert.NotEqual(t, "", person.ID)301 assert.NotEmpty(t, person.Name)302 assert.NotEmpty(t, person.ID)303 c.String(http.StatusOK, "ShouldBindUri test OK")304 })305306 path, _ := exampleFromPath("/rest/:name/:id")
12 unmodified lines
319 }320 router.Handle(http.MethodGet, "/rest/:name/:id", func(c *Context) {321 var person Person322 require.NoError(t, c.BindUri(&person))323 assert.NotEqual(t, "", person.Name)324 assert.NotEqual(t, "", person.ID)323 assert.NotEmpty(t, person.Name)324 assert.NotEmpty(t, person.ID)325 c.String(http.StatusOK, "BindUri test OK")326 })327328 path, _ := exampleFromPath("/rest/:name/:id")
148 unmodified lines
modified:logger_test.go+2 added-2 removed
369 unmodified lines
370 })371372 w := PerformRequest(router, http.MethodGet, "/error")373 assert.Equal(t, http.StatusOK, w.Code)374 assert.Equal(t, "{\"error\":\"this is an error\"}", w.Body.String())374 assert.JSONEq(t, "{\"error\":\"this is an error\"}", w.Body.String())375376 w = PerformRequest(router, http.MethodGet, "/abort")377 assert.Equal(t, http.StatusUnauthorized, w.Code)378 assert.Equal(t, "{\"error\":\"no authorized\"}", w.Body.String())378 assert.JSONEq(t, "{\"error\":\"no authorized\"}", w.Body.String())379380 w = PerformRequest(router, http.MethodGet, "/print")381 assert.Equal(t, http.StatusInternalServerError, w.Code)382 assert.Equal(t, "hola!{\"error\":\"this is an error\"}", w.Body.String())
74 unmodified lines
modified:middleware_test.go+1 added-1 removed
247 unmodified lines
248249 w := PerformRequest(router, http.MethodGet, "/")250251 assert.Equal(t, http.StatusBadRequest, w.Code)252 assert.Equal(t, strings.Replace("hola\n<map><foo>bar</foo></map>{\"foo\":\"bar\"}{\"foo\":\"bar\"}event:test\ndata:message\n\n", " ", "", -1), strings.Replace(w.Body.String(), " ", "", -1))252 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(), " ", ""))253}
modified:mode.go+4 added-2 removed
42 unmodified lines
4344// DefaultErrorWriter is the default io.Writer used by Gin to debug errors45var DefaultErrorWriter io.Writer = os.Stderr4647var (47var ginMode int32 = debugCode48var modeName atomic.Value48 ginMode int32 = debugCode49 modeName atomic.Value50)5152func init() {53 mode := os.Getenv(EnvGinMode)54 SetMode(mode)
46 unmodified lines
modified:routes_test.go+2 added-2 removed
482 unmodified lines
483 assert.Equal(t, http.StatusOK, w.Code)484 assert.Contains(t, w.Body.String(), "package gin")485 // Content-Type='text/plain; charset=utf-8' when go version <= 1.16,486 // else, Content-Type='text/x-go; charset=utf-8'487 assert.NotEqual(t, "", w.Header().Get("Content-Type"))487 assert.NotEmpty(t, w.Header().Get("Content-Type"))488 assert.NotEqual(t, "Mon, 02 Jan 2006 15:04:05 MST", w.Header().Get("Last-Modified"))489 assert.Equal(t, "Mon, 02 Jan 2006 15:04:05 MST", w.Header().Get("Expires"))490 assert.Equal(t, "Gin Framework", w.Header().Get("x-GIN"))491}
271 unmodified lines
763764 // Test not found765 router.Use(func(c *Context) {766 // For not found routes full path is empty767 assert.Equal(t, "", c.FullPath())767 assert.Empty(t, c.FullPath())768 })769770 w := PerformRequest(router, http.MethodGet, "/not-found")771 assert.Equal(t, http.StatusNotFound, w.Code)
20 unmodified lines
modified:tree_test.go+3 added-3 removed
479 unmodified lines
480 t.Fatalf("no panic while inserting duplicate route '%s", route)481 }482 }483484 //printChildren(tree, "")484 // printChildren(tree, "")485486 checkRequests(t, tree, testRequests{487 {"/", false, "/", nil},488 {"/doc/", false, "/doc/", nil},
42 unmodified lines
531}532533func TestTreeCatchMaxParams(t *testing.T) {534 tree := &node{}535 var route = "/cmd/*filepath"535 route := "/cmd/*filepath"536 tree.addRoute(route, fakeHandler(route))537}538539func TestTreeDoubleWildcard(t *testing.T) {
151 unmodified lines
691 }692}693694func TestRedirectTrailingSlash(t *testing.T) {695 var data = []struct {695 data := []struct {696 path string697 }{698 {"/hello/:name"},699 {"/hello/:name/123"},
321 unmodified lines
modified:utils_test.go+1 added-1 removed
92 unmodified lines
93 // this empty function is used by TestFunctionName()94}9596func TestJoinPaths(t *testing.T) {97 assert.Equal(t, "", joinPaths("", ""))97 assert.Empty(t, joinPaths("", ""))98 assert.Equal(t, "/", joinPaths("", "/"))99 assert.Equal(t, "/a", joinPaths("/a", ""))100 assert.Equal(t, "/a/", joinPaths("/a/", ""))101 assert.Equal(t, "/a/", joinPaths("/a/", "/"))
49 unmodified lines