Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

faat(encoding/form): allow change the default encoder and decoder tag name #3328

Merged
merged 1 commit into from
Jun 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions encoding/form/form.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,13 @@ var (
decoder = form.NewDecoder()
)

// This variable can be replaced with -ldflags like below:
// go build "-ldflags=-X github.com/go-kratos/kratos/v2/encoding/form.tagName=form"
var tagName = "json"

func init() {
decoder.SetTagName("json")
encoder.SetTagName("json")
decoder.SetTagName(tagName)
encoder.SetTagName(tagName)
encoding.RegisterCodec(codec{encoder: encoder, decoder: decoder})
}

Expand Down
62 changes: 62 additions & 0 deletions encoding/form/form_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,68 @@ import (
ectest "github.com/go-kratos/kratos/v2/internal/testdata/encoding"
)

// This variable can be replaced with -ldflags like below:
// go test "-ldflags=-X github.com/go-kratos/kratos/v2/encoding/form.tagNameTest=form"
var tagNameTest string

func init() {
if tagNameTest == "" {
tagNameTest = tagName
}
}

func TestFormEncoderAndDecoder(t *testing.T) {
t.Cleanup(func() {
encoder.SetTagName(tagName)
decoder.SetTagName(tagName)
})

encoder.SetTagName(tagNameTest)
decoder.SetTagName(tagNameTest)

type testFormTagName struct {
Name string `form:"name_form" json:"name_json"`
}
v, err := encoder.Encode(&testFormTagName{
Name: "test tag name",
})
if err != nil {
t.Fatal(err)
}
jsonName := v.Get("name_json")
formName := v.Get("name_form")
switch tagNameTest {
case "json":
if jsonName != "test tag name" {
t.Errorf("got: %s", jsonName)
}
if formName != "" {
t.Errorf("want: empty, got: %s", formName)
}
case "form":
if formName != "test tag name" {
t.Errorf("got: %s", formName)
}
if jsonName != "" {
t.Errorf("want: empty, got: %s", jsonName)
}
default:
t.Fatalf("unknown tag name: %s", tagNameTest)
}

var tn *testFormTagName
err = decoder.Decode(&tn, v)
if err != nil {
t.Fatal(err)
}
if tn == nil {
t.Fatal("nil tag name")
}
if tn.Name != "test tag name" {
t.Errorf("got %s", tn.Name)
}
}

type LoginRequest struct {
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
Expand Down
Loading