Skip to content

Commit

Permalink
faat(encoding/form): allow change the default form encoder and decode…
Browse files Browse the repository at this point in the history
…r tag name
  • Loading branch information
demoManito committed May 22, 2024
1 parent d0d5761 commit 1ef4223
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 2 deletions.
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
63 changes: 63 additions & 0 deletions encoding/form/form_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ 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
}
}

type LoginRequest struct {
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
Expand Down Expand Up @@ -219,3 +229,56 @@ func TestOptional(t *testing.T) {
t.Fatalf("got %s", query.Encode())
}
}

type testFormTagName struct {
Name string `form:"name_form" json:"name_json"`
}

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

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

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)
}
}

0 comments on commit 1ef4223

Please sign in to comment.