Repository: go-kratos/kratos
Pull request #3234 (2024-03-12 13:03:12)

fix(encoding/form): optimize EncodeField and add test cases
<!--
🎉 Thanks for sending a pull request to Kratos! Here are some tips for you:

1. If this is your first time contributing to Kratos, please read our contribution guide: https://go-kratos.dev/en/docs/community/contribution/
2. Ensure you have added or ran the appropriate tests and lint for your PR, please use `make lint` and `make test` before filing your PR, use `make clean` to tidy your go mod.
3. If the PR is unfinished, you may need to mark it as a WIP(Work In Progress) PR or Draft PR
4. Please use a semantic commits format title, such as `<type>[optional scope]: <description>`, see: https://go-kratos.dev/docs/community/contribution#type
5. at the same time, please note that similar work should be submitted in one PR as far as possible to reduce the workload of reviewers. Do not split a work into multiple PR unless it should.
-->

<!--
🎉 感谢您向 Kratos 发送 PR！以下是一些提示：
如果这是你第一次为 Kratos 贡献，请阅读我们的贡献指南：https://go-kratos.dev/en/docs/community/contribution/
2、确保您已经为您的 PR 添加或运行了适当的测试和lint，请在提交PR之前使用“make lint”和“make test”，使用“make clean”整理您的 go.mod。
3、如果 PR 未完成，您可能需要将其标记为 WIP（Work In Progress）PR 或 Draft PR
4、请使用语义提交格式标题，如“<类型>[可选范围]：<说明>`，请参阅：https://go-kratos.dev/docs/community/contribution#type
5. 同时请注意，同类的工作请尽量在一个PR中提交，以减轻 review 者的工作负担，不要把一项工作拆分成很多个PR，除非它应该这样做。
-->


#### Description (what this PR does / why we need it):
<!--
* The description should include the motivation for this PR or contrast this with previous behavior
-->
- remove protoreflect.StringKind convert to string
![image](https://github.com/go-kratos/kratos/assets/27986239/ff544e6f-31ed-414a-b037-98cb7703a69d)

- supplementary encode map test cases

#### Which issue(s) this PR fixes (resolves / be part of):
<!--
* Automatically closes linked issue when PR is merged.
* If your PR is not fully resolved the issue, please use `part of #<issue number>` instead.

Usage: `fixes/resolves #<issue number>`, or `fixes/resolves (paste link of issue)`.
-->


#### Other special notes for the reviewers:
<!--
* Somethings that need extra attention for the reviewers
* Some additional notes, TODO list, etc.
-->



Patch:
diff --git a/contrib/registry/consul/registry.go b/contrib/registry/consul/registry.go
index 8105ab1d..c83fa74c 100644
--- a/contrib/registry/consul/registry.go
+++ b/contrib/registry/consul/registry.go
@@ -190,6 +190,7 @@ func (r *Registry) Watch(ctx context.Context, name string) (registry.Watcher, er
 			services:    &atomic.Value{},
 			serviceName: name,
 		}
+		set.ctx, set.cancel = context.WithCancel(context.Background())
 		r.registry[name] = set
 	}
 
@@ -208,10 +209,8 @@ func (r *Registry) Watch(ctx context.Context, name string) (registry.Watcher, er
 		// otherwise the initial data may be blocked forever during the watch.
 		w.event <- struct{}{}
 	}
-
 	if !ok {
-		err := r.resolve(ctx, set)
-		if err != nil {
+		if err := r.resolve(set.ctx, set); err != nil {
 			return nil, err
 		}
 	}
@@ -249,6 +248,9 @@ func (r *Registry) resolve(ctx context.Context, ss *serviceSet) error {
 				}
 				idx = tmpIdx
 			case <-ctx.Done():
+				r.lock.Lock()
+				delete(r.registry, ss.serviceName)
+				r.lock.Unlock()
 				return
 			}
 		}
diff --git a/contrib/registry/consul/service.go b/contrib/registry/consul/service.go
index a0a16609..6567b772 100644
--- a/contrib/registry/consul/service.go
+++ b/contrib/registry/consul/service.go
@@ -1,6 +1,7 @@
 package consul
 
 import (
+	"context"
 	"sync"
 	"sync/atomic"
 
@@ -12,6 +13,9 @@ type serviceSet struct {
 	watcher     map[*watcher]struct{}
 	services    *atomic.Value
 	lock        sync.RWMutex
+
+	ctx    context.Context
+	cancel context.CancelFunc
 }
 
 func (s *serviceSet) broadcast(ss []*registry.ServiceInstance) {
diff --git a/contrib/registry/consul/watcher.go b/contrib/registry/consul/watcher.go
index 0a5d3575..f84caeb4 100644
--- a/contrib/registry/consul/watcher.go
+++ b/contrib/registry/consul/watcher.go
@@ -36,5 +36,9 @@ func (w *watcher) Stop() error {
 	w.set.lock.Lock()
 	defer w.set.lock.Unlock()
 	delete(w.set.watcher, w)
+	// close resolve
+	if len(w.set.watcher) == 0 {
+		w.set.cancel()
+	}
 	return nil
 }
diff --git a/contrib/registry/nacos/watcher.go b/contrib/registry/nacos/watcher.go
index 78b4fc21..6fd59b37 100644
--- a/contrib/registry/nacos/watcher.go
+++ b/contrib/registry/nacos/watcher.go
@@ -14,14 +14,15 @@ import (
 var _ registry.Watcher = (*watcher)(nil)
 
 type watcher struct {
-	serviceName string
-	clusters    []string
-	groupName   string
-	ctx         context.Context
-	cancel      context.CancelFunc
-	watchChan   chan struct{}
-	cli         naming_client.INamingClient
-	kind        string
+	serviceName    string
+	clusters       []string
+	groupName      string
+	ctx            context.Context
+	cancel         context.CancelFunc
+	watchChan      chan struct{}
+	cli            naming_client.INamingClient
+	kind           string
+	subscribeParam *vo.SubscribeParam
 }
 
 func newWatcher(ctx context.Context, cli naming_client.INamingClient, serviceName, groupName, kind string, clusters []string) (*watcher, error) {
@@ -35,14 +36,15 @@ func newWatcher(ctx context.Context, cli naming_client.INamingClient, serviceNam
 	}
 	w.ctx, w.cancel = context.WithCancel(ctx)
 
-	e := w.cli.Subscribe(&vo.SubscribeParam{
+	w.subscribeParam = &vo.SubscribeParam{
 		ServiceName: serviceName,
 		Clusters:    clusters,
 		GroupName:   groupName,
 		SubscribeCallback: func(services []model.SubscribeService, err error) {
 			w.watchChan <- struct{}{}
 		},
-	})
+	}
+	e := w.cli.Subscribe(w.subscribeParam)
 	return w, e
 }
 
@@ -78,10 +80,7 @@ func (w *watcher) Next() ([]*registry.ServiceInstance, error) {
 }
 
 func (w *watcher) Stop() error {
+	err := w.cli.Unsubscribe(w.subscribeParam)
 	w.cancel()
-	return w.cli.Unsubscribe(&vo.SubscribeParam{
-		ServiceName: w.serviceName,
-		GroupName:   w.groupName,
-		Clusters:    w.clusters,
-	})
+	return err
 }
diff --git a/encoding/form/proto_encode.go b/encoding/form/proto_encode.go
index 584b1da5..67b92f92 100644
--- a/encoding/form/proto_encode.go
+++ b/encoding/form/proto_encode.go
@@ -137,14 +137,12 @@ func EncodeField(fieldDescriptor protoreflect.FieldDescriptor, value protoreflec
 		}
 		desc := fieldDescriptor.Enum().Values().ByNumber(value.Enum())
 		return string(desc.Name()), nil
-	case protoreflect.StringKind:
-		return value.String(), nil
 	case protoreflect.BytesKind:
 		return base64.URLEncoding.EncodeToString(value.Bytes()), nil
 	case protoreflect.MessageKind, protoreflect.GroupKind:
 		return encodeMessage(fieldDescriptor.Message(), value)
 	default:
-		return fmt.Sprint(value.Interface()), nil
+		return value.String(), nil
 	}
 }
 
diff --git a/transport/http/context.go b/transport/http/context.go
index ab9a1d39..43ea78ce 100644
--- a/transport/http/context.go
+++ b/transport/http/context.go
@@ -57,6 +57,7 @@ func (w *responseWriter) Write(data []byte) (int, error) {
 	w.w.WriteHeader(w.code)
 	return w.w.Write(data)
 }
+func (w *responseWriter) Unwrap() http.ResponseWriter { return w.w }
 
 type wrapper struct {
 	router *Router


Test patch:
diff --git a/contrib/registry/consul/registry_test.go b/contrib/registry/consul/registry_test.go
index 02b61720..d6799b69 100644
--- a/contrib/registry/consul/registry_test.go
+++ b/contrib/registry/consul/registry_test.go
@@ -413,6 +413,226 @@ func TestRegistry_Watch(t *testing.T) {
 	}
 }
 
+func TestRegistry_IdleAndWatch(t *testing.T) {
+	addr := fmt.Sprintf("%s:9091", getIntranetIP())
+
+	time.Sleep(time.Millisecond * 100)
+	cli, err := api.NewClient(&api.Config{Address: "127.0.0.1:8500", WaitTime: 2 * time.Second})
+	if err != nil {
+		t.Fatalf("create consul client failed: %v", err)
+	}
+
+	r := New(cli, []Option{
+		WithHealthCheck(false),
+	}...)
+
+	instance1 := &registry.ServiceInstance{
+		ID:        "1",
+		Name:      "server-1",
+		Version:   "v0.0.1",
+		Endpoints: []string{fmt.Sprintf("tcp://%s?isSecure=false", addr)},
+	}
+
+	type args struct {
+		ctx      context.Context
+		instance *registry.ServiceInstance
+	}
+
+	tests := []struct {
+		name    string
+		args    args
+		want    []*registry.ServiceInstance
+		wantErr bool
+	}{
+		{
+			name: "many client, one idle",
+			args: args{
+				ctx:      context.Background(),
+				instance: instance1,
+			},
+			want:    []*registry.ServiceInstance{instance1},
+			wantErr: false,
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			err = r.Register(tt.args.ctx, tt.args.instance)
+			if err != nil {
+				t.Error(err)
+			}
+			defer func() {
+				err = r.Deregister(tt.args.ctx, tt.args.instance)
+				if err != nil {
+					t.Error(err)
+				}
+			}()
+
+			for i := 0; i < 10; i++ {
+				watch, err1 := r.Watch(context.Background(), tt.args.instance.Name)
+				if err1 != nil {
+					t.Error(err1)
+				}
+				go func(i int) {
+					// first
+					service, err2 := watch.Next()
+					if (err2 != nil) != tt.wantErr {
+						t.Errorf("GetService() error = %v, wantErr %v", err, tt.wantErr)
+						t.Errorf("GetService() got = %v", service)
+						return
+					}
+					// instance changes
+					service, err2 = watch.Next()
+					if i == 9 {
+						return
+					}
+					if (err2 != nil) != tt.wantErr {
+						t.Errorf("GetService() error = %v, wantErr %v", err, tt.wantErr)
+						t.Errorf("GetService() got = %v", service)
+						return
+					}
+					if !reflect.DeepEqual(service, tt.want) {
+						t.Errorf("GetService() got = %v, want %v", service, tt.want)
+					}
+					// t.Logf("service:%v, i:%d", service, i)
+				}(i)
+				if i == 9 {
+					time.Sleep(time.Second * 3)
+					// become idle, close watcher
+					err1 = watch.Stop()
+					if err1 != nil {
+						t.Errorf("watch stop err:%v", err)
+					}
+				}
+			}
+			time.Sleep(2 * time.Second)
+			change := tt.args.instance
+			change.Version = "v0.0.2"
+			err = r.Register(tt.args.ctx, change)
+			if err != nil {
+				t.Error(err)
+			}
+			time.Sleep(1 * time.Second)
+		})
+	}
+}
+
+func TestRegistry_IdleAndWatch2(t *testing.T) {
+	addr := fmt.Sprintf("%s:9091", getIntranetIP())
+
+	time.Sleep(time.Millisecond * 100)
+	cli, err := api.NewClient(&api.Config{Address: "127.0.0.1:8500", WaitTime: 2 * time.Second})
+	if err != nil {
+		t.Fatalf("create consul client failed: %v", err)
+	}
+
+	instance1 := &registry.ServiceInstance{
+		ID:        "1",
+		Name:      "server-1",
+		Version:   "v0.0.1",
+		Endpoints: []string{fmt.Sprintf("tcp://%s?isSecure=false", addr)},
+	}
+	type args struct {
+		ctx      context.Context
+		opts     []Option
+		instance *registry.ServiceInstance
+	}
+
+	tests := []struct {
+		name    string
+		args    args
+		want    []*registry.ServiceInstance
+		wantErr bool
+	}{
+		{
+			name: "all clients are idle, create a new one",
+			args: args{
+				ctx:      context.Background(),
+				instance: instance1,
+				opts: []Option{
+					WithHealthCheck(false),
+				},
+			},
+			want:    []*registry.ServiceInstance{instance1},
+			wantErr: false,
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			r := New(cli, tt.args.opts...)
+
+			err = r.Register(tt.args.ctx, tt.args.instance)
+			if err != nil {
+				t.Error(err)
+			}
+			defer func() {
+				err = r.Deregister(tt.args.ctx, tt.args.instance)
+				if err != nil {
+					t.Error(err)
+				}
+			}()
+
+			ctx, cancel := context.WithCancel(context.Background())
+			for i := 0; i < 10; i++ {
+				stopCtx, stopCancel := context.WithCancel(ctx)
+				watch, err1 := r.Watch(context.Background(), tt.args.instance.Name)
+				if err1 != nil {
+					t.Error(err1)
+				}
+				go func(i int) {
+					// first
+					service, err2 := watch.Next()
+					if (err2 != nil) != tt.wantErr {
+						t.Errorf("GetService() error = %v, wantErr %v", err, tt.wantErr)
+						t.Errorf("GetService() got = %v", service)
+						return
+					}
+					_, err2 = watch.Next()
+					if err2 == nil {
+						t.Errorf("watch exit exception:%d ", i)
+					}
+				}(i)
+				go func() {
+					select {
+					case <-stopCtx.Done():
+						err1 = watch.Stop()
+						if err1 != nil {
+							t.Errorf("watch stop err:%v", err)
+						}
+						return
+					case <-time.After(time.Minute):
+						stopCancel()
+						err1 = watch.Stop()
+						if err1 != nil {
+							t.Errorf("watch stop err:%v", err)
+						}
+						return
+					}
+				}()
+			}
+			time.Sleep(time.Second * 3)
+			cancel()
+			time.Sleep(time.Second * 2)
+			// Everything is idle. Add new watch.
+			watchCtx := context.Background()
+			watch, err := r.Watch(watchCtx, tt.args.instance.Name)
+			if err != nil {
+				t.Error(err)
+			}
+			service, err := watch.Next()
+			if (err != nil) != tt.wantErr {
+				t.Errorf("GetService() error = %v, wantErr %v", err, tt.wantErr)
+				t.Errorf("GetService() got = %v", service)
+				return
+			}
+			if !reflect.DeepEqual(service, tt.want) {
+				t.Errorf("GetService() got = %v, want %v", service, tt.want)
+			}
+		})
+	}
+}
+
 func getIntranetIP() string {
 	addrs, err := net.InterfaceAddrs()
 	if err != nil {
diff --git a/encoding/form/proto_encode_test.go b/encoding/form/proto_encode_test.go
index 1b4e11e3..a2dee35d 100644
--- a/encoding/form/proto_encode_test.go
+++ b/encoding/form/proto_encode_test.go
@@ -18,19 +18,20 @@ func TestEncodeValues(t *testing.T) {
 	t.Cleanup(func() { time.Local = loc })
 
 	in := &complex.Complex{
-		Id:      2233,
-		NoOne:   "2233",
-		Simple:  &complex.Simple{Component: "5566"},
-		Simples: []string{"3344", "5566"},
-		B:       true,
-		Sex:     complex.Sex_woman,
-		Age:     18,
-		A:       19,
-		Count:   3,
-		Price:   11.23,
-		D:       22.22,
-		Byte:    []byte("123"),
-		Map:     map[string]string{"kratos": "https://go-kratos.dev/", "kratos_start": "https://go-kratos.dev/en/docs/getting-started/start/"},
+		Id:          2233,
+		NoOne:       "2233",
+		Simple:      &complex.Simple{Component: "5566"},
+		Simples:     []string{"3344", "5566"},
+		B:           true,
+		Sex:         complex.Sex_woman,
+		Age:         18,
+		A:           19,
+		Count:       3,
+		Price:       11.23,
+		D:           22.22,
+		Byte:        []byte("123"),
+		Map:         map[string]string{"kratos": "https://go-kratos.dev/", "kratos_start": "https://go-kratos.dev/en/docs/getting-started/start/"},
+		MapInt64Key: map[int64]string{1: "kratos", 2: "go-zero"},
 
 		Timestamp: &timestamppb.Timestamp{Seconds: 20, Nanos: 2},
 		Duration:  &durationpb.Duration{Seconds: 120, Nanos: 22},
@@ -49,9 +50,9 @@ func TestEncodeValues(t *testing.T) {
 	if err != nil {
 		t.Fatal(err)
 	}
-	want := "a=19&age=18&b=true&bool=false&byte=MTIz&bytes=MTIz&count=3&d=22.22&double=12.33&duration=2m0.000000022s&field=1%2C2&float=12.34&id=2233&int32=32&int64=64&map%5Bkratos%5D=https%3A%2F%2Fgo-kratos.dev%2F&map%5Bkratos_start%5D=https%3A%2F%2Fgo-kratos.dev%2Fen%2Fdocs%2Fgetting-started%2Fstart%2F&numberOne=2233&price=11.23&sex=woman&simples=3344&simples=5566&string=go-kratos&timestamp=1970-01-01T00%3A00%3A20.000000002Z&uint32=32&uint64=64&very_simple.component=5566" // nolint:lll
+	want := "a=19&age=18&b=true&bool=false&byte=MTIz&bytes=MTIz&count=3&d=22.22&double=12.33&duration=2m0.000000022s&field=1%2C2&float=12.34&id=2233&int32=32&int64=64&map%5Bkratos%5D=https%3A%2F%2Fgo-kratos.dev%2F&map%5Bkratos_start%5D=https%3A%2F%2Fgo-kratos.dev%2Fen%2Fdocs%2Fgetting-started%2Fstart%2F&map_int64_key%5B1%5D=kratos&map_int64_key%5B2%5D=go-zero&numberOne=2233&price=11.23&sex=woman&simples=3344&simples=5566&string=go-kratos&timestamp=1970-01-01T00%3A00%3A20.000000002Z&uint32=32&uint64=64&very_simple.component=5566" // nolint:lll
 	if got := query.Encode(); want != got {
-		t.Errorf("want: %s, got: %s", want, got)
+		t.Errorf("\nwant: %s, \ngot: %s", want, got)
 	}
 }
 
diff --git a/internal/testdata/complex/complex.pb.go b/internal/testdata/complex/complex.pb.go
index e11b9d4b..216c3617 100644
--- a/internal/testdata/complex/complex.pb.go
+++ b/internal/testdata/complex/complex.pb.go
@@ -1,7 +1,7 @@
 // Code generated by protoc-gen-go. DO NOT EDIT.
 // versions:
 // 	protoc-gen-go v1.27.1
-// 	protoc        v3.17.3
+// 	protoc        v3.19.1
 // source: complex.proto
 
 package complex
@@ -77,31 +77,32 @@ type Complex struct {
 	unknownFields protoimpl.UnknownFields
 
 	// Id represents the message identifier.
-	Id        int64                   `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
-	NoOne     string                  `protobuf:"bytes,2,opt,name=no_one,json=numberOne,proto3" json:"no_one,omitempty"`
-	Simple    *Simple                 `protobuf:"bytes,3,opt,name=simple,json=very_simple,proto3" json:"simple,omitempty"`
-	Simples   []string                `protobuf:"bytes,4,rep,name=simples,proto3" json:"simples,omitempty"`
-	B         bool                    `protobuf:"varint,5,opt,name=b,proto3" json:"b,omitempty"`
-	Sex       Sex                     `protobuf:"varint,6,opt,name=sex,proto3,enum=testproto.Sex" json:"sex,omitempty"`
-	Age       int32                   `protobuf:"varint,7,opt,name=age,proto3" json:"age,omitempty"`
-	A         uint32                  `protobuf:"varint,8,opt,name=a,proto3" json:"a,omitempty"`
-	Count     uint64                  `protobuf:"varint,9,opt,name=count,proto3" json:"count,omitempty"`
-	Price     float32                 `protobuf:"fixed32,10,opt,name=price,proto3" json:"price,omitempty"`
-	D         float64                 `protobuf:"fixed64,11,opt,name=d,proto3" json:"d,omitempty"`
-	Byte      []byte                  `protobuf:"bytes,12,opt,name=byte,proto3" json:"byte,omitempty"`
-	Timestamp *timestamppb.Timestamp  `protobuf:"bytes,13,opt,name=timestamp,proto3" json:"timestamp,omitempty"`
-	Duration  *durationpb.Duration    `protobuf:"bytes,14,opt,name=duration,proto3" json:"duration,omitempty"`
-	Field     *fieldmaskpb.FieldMask  `protobuf:"bytes,15,opt,name=field,proto3" json:"field,omitempty"`
-	Double    *wrapperspb.DoubleValue `protobuf:"bytes,16,opt,name=double,proto3" json:"double,omitempty"`
-	Float     *wrapperspb.FloatValue  `protobuf:"bytes,17,opt,name=float,proto3" json:"float,omitempty"`
-	Int64     *wrapperspb.Int64Value  `protobuf:"bytes,18,opt,name=int64,proto3" json:"int64,omitempty"`
-	Int32     *wrapperspb.Int32Value  `protobuf:"bytes,19,opt,name=int32,proto3" json:"int32,omitempty"`
-	Uint64    *wrapperspb.UInt64Value `protobuf:"bytes,20,opt,name=uint64,proto3" json:"uint64,omitempty"`
-	Uint32    *wrapperspb.UInt32Value `protobuf:"bytes,21,opt,name=uint32,proto3" json:"uint32,omitempty"`
-	Bool      *wrapperspb.BoolValue   `protobuf:"bytes,22,opt,name=bool,proto3" json:"bool,omitempty"`
-	String_   *wrapperspb.StringValue `protobuf:"bytes,23,opt,name=string,proto3" json:"string,omitempty"`
-	Bytes     *wrapperspb.BytesValue  `protobuf:"bytes,24,opt,name=bytes,proto3" json:"bytes,omitempty"`
-	Map       map[string]string       `protobuf:"bytes,25,rep,name=map,proto3" json:"map,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+	Id          int64                   `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
+	NoOne       string                  `protobuf:"bytes,2,opt,name=no_one,json=numberOne,proto3" json:"no_one,omitempty"`
+	Simple      *Simple                 `protobuf:"bytes,3,opt,name=simple,json=very_simple,proto3" json:"simple,omitempty"`
+	Simples     []string                `protobuf:"bytes,4,rep,name=simples,proto3" json:"simples,omitempty"`
+	B           bool                    `protobuf:"varint,5,opt,name=b,proto3" json:"b,omitempty"`
+	Sex         Sex                     `protobuf:"varint,6,opt,name=sex,proto3,enum=testproto.Sex" json:"sex,omitempty"`
+	Age         int32                   `protobuf:"varint,7,opt,name=age,proto3" json:"age,omitempty"`
+	A           uint32                  `protobuf:"varint,8,opt,name=a,proto3" json:"a,omitempty"`
+	Count       uint64                  `protobuf:"varint,9,opt,name=count,proto3" json:"count,omitempty"`
+	Price       float32                 `protobuf:"fixed32,10,opt,name=price,proto3" json:"price,omitempty"`
+	D           float64                 `protobuf:"fixed64,11,opt,name=d,proto3" json:"d,omitempty"`
+	Byte        []byte                  `protobuf:"bytes,12,opt,name=byte,proto3" json:"byte,omitempty"`
+	Timestamp   *timestamppb.Timestamp  `protobuf:"bytes,13,opt,name=timestamp,proto3" json:"timestamp,omitempty"`
+	Duration    *durationpb.Duration    `protobuf:"bytes,14,opt,name=duration,proto3" json:"duration,omitempty"`
+	Field       *fieldmaskpb.FieldMask  `protobuf:"bytes,15,opt,name=field,proto3" json:"field,omitempty"`
+	Double      *wrapperspb.DoubleValue `protobuf:"bytes,16,opt,name=double,proto3" json:"double,omitempty"`
+	Float       *wrapperspb.FloatValue  `protobuf:"bytes,17,opt,name=float,proto3" json:"float,omitempty"`
+	Int64       *wrapperspb.Int64Value  `protobuf:"bytes,18,opt,name=int64,proto3" json:"int64,omitempty"`
+	Int32       *wrapperspb.Int32Value  `protobuf:"bytes,19,opt,name=int32,proto3" json:"int32,omitempty"`
+	Uint64      *wrapperspb.UInt64Value `protobuf:"bytes,20,opt,name=uint64,proto3" json:"uint64,omitempty"`
+	Uint32      *wrapperspb.UInt32Value `protobuf:"bytes,21,opt,name=uint32,proto3" json:"uint32,omitempty"`
+	Bool        *wrapperspb.BoolValue   `protobuf:"bytes,22,opt,name=bool,proto3" json:"bool,omitempty"`
+	String_     *wrapperspb.StringValue `protobuf:"bytes,23,opt,name=string,proto3" json:"string,omitempty"`
+	Bytes       *wrapperspb.BytesValue  `protobuf:"bytes,24,opt,name=bytes,proto3" json:"bytes,omitempty"`
+	Map         map[string]string       `protobuf:"bytes,25,rep,name=map,proto3" json:"map,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+	MapInt64Key map[int64]string        `protobuf:"bytes,26,rep,name=map_int64_key,proto3" json:"map_int64_key,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
 }
 
 func (x *Complex) Reset() {
@@ -311,6 +312,13 @@ func (x *Complex) GetMap() map[string]string {
 	return nil
 }
 
+func (x *Complex) GetMapInt64Key() map[int64]string {
+	if x != nil {
+		return x.MapInt64Key
+	}
+	return nil
+}
+
 type Simple struct {
 	state         protoimpl.MessageState
 	sizeCache     protoimpl.SizeCache
@@ -370,7 +378,7 @@ var file_complex_proto_rawDesc = []byte{
 	0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x66, 0x69, 0x65,
 	0x6c, 0x64, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67,
 	0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77,
-	0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xfa, 0x07,
+	0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x85, 0x09,
 	0x0a, 0x07, 0x43, 0x6f, 0x6d, 0x70, 0x6c, 0x65, 0x78, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18,
 	0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x02, 0x69, 0x64, 0x12, 0x19, 0x0a, 0x06, 0x6e, 0x6f, 0x5f,
 	0x6f, 0x6e, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x6e, 0x75, 0x6d, 0x62, 0x65,
@@ -431,20 +439,29 @@ var file_complex_proto_rawDesc = []byte{
 	0x74, 0x65, 0x73, 0x12, 0x2d, 0x0a, 0x03, 0x6d, 0x61, 0x70, 0x18, 0x19, 0x20, 0x03, 0x28, 0x0b,
 	0x32, 0x1b, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x43, 0x6f, 0x6d,
 	0x70, 0x6c, 0x65, 0x78, 0x2e, 0x4d, 0x61, 0x70, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x03, 0x6d,
-	0x61, 0x70, 0x1a, 0x36, 0x0a, 0x08, 0x4d, 0x61, 0x70, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10,
-	0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79,
-	0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52,
-	0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x26, 0x0a, 0x06, 0x53, 0x69,
-	0x6d, 0x70, 0x6c, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x63, 0x6f, 0x6d, 0x70, 0x6f, 0x6e, 0x65, 0x6e,
-	0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x63, 0x6f, 0x6d, 0x70, 0x6f, 0x6e, 0x65,
-	0x6e, 0x74, 0x2a, 0x19, 0x0a, 0x03, 0x73, 0x65, 0x78, 0x12, 0x07, 0x0a, 0x03, 0x6d, 0x61, 0x6e,
-	0x10, 0x00, 0x12, 0x09, 0x0a, 0x05, 0x77, 0x6f, 0x6d, 0x61, 0x6e, 0x10, 0x01, 0x42, 0x57, 0x5a,
-	0x55, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x2d, 0x6b,
-	0x72, 0x61, 0x74, 0x6f, 0x73, 0x2f, 0x6b, 0x72, 0x61, 0x74, 0x6f, 0x73, 0x2f, 0x63, 0x6d, 0x64,
-	0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x2d, 0x67, 0x65, 0x6e, 0x2d, 0x67, 0x6f, 0x2d, 0x68,
-	0x74, 0x74, 0x70, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x65, 0x6e, 0x63,
-	0x6f, 0x64, 0x69, 0x6e, 0x67, 0x2f, 0x63, 0x6f, 0x6d, 0x70, 0x6c, 0x65, 0x78, 0x2f, 0x3b, 0x63,
-	0x6f, 0x6d, 0x70, 0x6c, 0x65, 0x78, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
+	0x61, 0x70, 0x12, 0x49, 0x0a, 0x0d, 0x6d, 0x61, 0x70, 0x5f, 0x69, 0x6e, 0x74, 0x36, 0x34, 0x5f,
+	0x6b, 0x65, 0x79, 0x18, 0x1a, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x23, 0x2e, 0x74, 0x65, 0x73, 0x74,
+	0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x43, 0x6f, 0x6d, 0x70, 0x6c, 0x65, 0x78, 0x2e, 0x4d, 0x61,
+	0x70, 0x49, 0x6e, 0x74, 0x36, 0x34, 0x4b, 0x65, 0x79, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x0d,
+	0x6d, 0x61, 0x70, 0x5f, 0x69, 0x6e, 0x74, 0x36, 0x34, 0x5f, 0x6b, 0x65, 0x79, 0x1a, 0x36, 0x0a,
+	0x08, 0x4d, 0x61, 0x70, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79,
+	0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76,
+	0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75,
+	0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x3e, 0x0a, 0x10, 0x4d, 0x61, 0x70, 0x49, 0x6e, 0x74, 0x36,
+	0x34, 0x4b, 0x65, 0x79, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79,
+	0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76,
+	0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75,
+	0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x26, 0x0a, 0x06, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x12,
+	0x1c, 0x0a, 0x09, 0x63, 0x6f, 0x6d, 0x70, 0x6f, 0x6e, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01,
+	0x28, 0x09, 0x52, 0x09, 0x63, 0x6f, 0x6d, 0x70, 0x6f, 0x6e, 0x65, 0x6e, 0x74, 0x2a, 0x19, 0x0a,
+	0x03, 0x73, 0x65, 0x78, 0x12, 0x07, 0x0a, 0x03, 0x6d, 0x61, 0x6e, 0x10, 0x00, 0x12, 0x09, 0x0a,
+	0x05, 0x77, 0x6f, 0x6d, 0x61, 0x6e, 0x10, 0x01, 0x42, 0x57, 0x5a, 0x55, 0x67, 0x69, 0x74, 0x68,
+	0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x2d, 0x6b, 0x72, 0x61, 0x74, 0x6f, 0x73,
+	0x2f, 0x6b, 0x72, 0x61, 0x74, 0x6f, 0x73, 0x2f, 0x63, 0x6d, 0x64, 0x2f, 0x70, 0x72, 0x6f, 0x74,
+	0x6f, 0x63, 0x2d, 0x67, 0x65, 0x6e, 0x2d, 0x67, 0x6f, 0x2d, 0x68, 0x74, 0x74, 0x70, 0x2f, 0x69,
+	0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67,
+	0x2f, 0x63, 0x6f, 0x6d, 0x70, 0x6c, 0x65, 0x78, 0x2f, 0x3b, 0x63, 0x6f, 0x6d, 0x70, 0x6c, 0x65,
+	0x78, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
 }
 
 var (
@@ -460,46 +477,48 @@ func file_complex_proto_rawDescGZIP() []byte {
 }
 
 var file_complex_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
-var file_complex_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
+var file_complex_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
 var file_complex_proto_goTypes = []interface{}{
 	(Sex)(0),                       // 0: testproto.sex
 	(*Complex)(nil),                // 1: testproto.Complex
 	(*Simple)(nil),                 // 2: testproto.Simple
 	nil,                            // 3: testproto.Complex.MapEntry
-	(*timestamppb.Timestamp)(nil),  // 4: google.protobuf.Timestamp
-	(*durationpb.Duration)(nil),    // 5: google.protobuf.Duration
-	(*fieldmaskpb.FieldMask)(nil),  // 6: google.protobuf.FieldMask
-	(*wrapperspb.DoubleValue)(nil), // 7: google.protobuf.DoubleValue
-	(*wrapperspb.FloatValue)(nil),  // 8: google.protobuf.FloatValue
-	(*wrapperspb.Int64Value)(nil),  // 9: google.protobuf.Int64Value
-	(*wrapperspb.Int32Value)(nil),  // 10: google.protobuf.Int32Value
-	(*wrapperspb.UInt64Value)(nil), // 11: google.protobuf.UInt64Value
-	(*wrapperspb.UInt32Value)(nil), // 12: google.protobuf.UInt32Value
-	(*wrapperspb.BoolValue)(nil),   // 13: google.protobuf.BoolValue
-	(*wrapperspb.StringValue)(nil), // 14: google.protobuf.StringValue
-	(*wrapperspb.BytesValue)(nil),  // 15: google.protobuf.BytesValue
+	nil,                            // 4: testproto.Complex.MapInt64KeyEntry
+	(*timestamppb.Timestamp)(nil),  // 5: google.protobuf.Timestamp
+	(*durationpb.Duration)(nil),    // 6: google.protobuf.Duration
+	(*fieldmaskpb.FieldMask)(nil),  // 7: google.protobuf.FieldMask
+	(*wrapperspb.DoubleValue)(nil), // 8: google.protobuf.DoubleValue
+	(*wrapperspb.FloatValue)(nil),  // 9: google.protobuf.FloatValue
+	(*wrapperspb.Int64Value)(nil),  // 10: google.protobuf.Int64Value
+	(*wrapperspb.Int32Value)(nil),  // 11: google.protobuf.Int32Value
+	(*wrapperspb.UInt64Value)(nil), // 12: google.protobuf.UInt64Value
+	(*wrapperspb.UInt32Value)(nil), // 13: google.protobuf.UInt32Value
+	(*wrapperspb.BoolValue)(nil),   // 14: google.protobuf.BoolValue
+	(*wrapperspb.StringValue)(nil), // 15: google.protobuf.StringValue
+	(*wrapperspb.BytesValue)(nil),  // 16: google.protobuf.BytesValue
 }
 var file_complex_proto_depIdxs = []int32{
 	2,  // 0: testproto.Complex.simple:type_name -> testproto.Simple
 	0,  // 1: testproto.Complex.sex:type_name -> testproto.sex
-	4,  // 2: testproto.Complex.timestamp:type_name -> google.protobuf.Timestamp
-	5,  // 3: testproto.Complex.duration:type_name -> google.protobuf.Duration
-	6,  // 4: testproto.Complex.field:type_name -> google.protobuf.FieldMask
-	7,  // 5: testproto.Complex.double:type_name -> google.protobuf.DoubleValue
-	8,  // 6: testproto.Complex.float:type_name -> google.protobuf.FloatValue
-	9,  // 7: testproto.Complex.int64:type_name -> google.protobuf.Int64Value
-	10, // 8: testproto.Complex.int32:type_name -> google.protobuf.Int32Value
-	11, // 9: testproto.Complex.uint64:type_name -> google.protobuf.UInt64Value
-	12, // 10: testproto.Complex.uint32:type_name -> google.protobuf.UInt32Value
-	13, // 11: testproto.Complex.bool:type_name -> google.protobuf.BoolValue
-	14, // 12: testproto.Complex.string:type_name -> google.protobuf.StringValue
-	15, // 13: testproto.Complex.bytes:type_name -> google.protobuf.BytesValue
+	5,  // 2: testproto.Complex.timestamp:type_name -> google.protobuf.Timestamp
+	6,  // 3: testproto.Complex.duration:type_name -> google.protobuf.Duration
+	7,  // 4: testproto.Complex.field:type_name -> google.protobuf.FieldMask
+	8,  // 5: testproto.Complex.double:type_name -> google.protobuf.DoubleValue
+	9,  // 6: testproto.Complex.float:type_name -> google.protobuf.FloatValue
+	10, // 7: testproto.Complex.int64:type_name -> google.protobuf.Int64Value
+	11, // 8: testproto.Complex.int32:type_name -> google.protobuf.Int32Value
+	12, // 9: testproto.Complex.uint64:type_name -> google.protobuf.UInt64Value
+	13, // 10: testproto.Complex.uint32:type_name -> google.protobuf.UInt32Value
+	14, // 11: testproto.Complex.bool:type_name -> google.protobuf.BoolValue
+	15, // 12: testproto.Complex.string:type_name -> google.protobuf.StringValue
+	16, // 13: testproto.Complex.bytes:type_name -> google.protobuf.BytesValue
 	3,  // 14: testproto.Complex.map:type_name -> testproto.Complex.MapEntry
-	15, // [15:15] is the sub-list for method output_type
-	15, // [15:15] is the sub-list for method input_type
-	15, // [15:15] is the sub-list for extension type_name
-	15, // [15:15] is the sub-list for extension extendee
-	0,  // [0:15] is the sub-list for field type_name
+	4,  // 15: testproto.Complex.map_int64_key:type_name -> testproto.Complex.MapInt64KeyEntry
+	16, // [16:16] is the sub-list for method output_type
+	16, // [16:16] is the sub-list for method input_type
+	16, // [16:16] is the sub-list for extension type_name
+	16, // [16:16] is the sub-list for extension extendee
+	0,  // [0:16] is the sub-list for field type_name
 }
 
 func init() { file_complex_proto_init() }
@@ -539,7 +558,7 @@ func file_complex_proto_init() {
 			GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
 			RawDescriptor: file_complex_proto_rawDesc,
 			NumEnums:      1,
-			NumMessages:   3,
+			NumMessages:   4,
 			NumExtensions: 0,
 			NumServices:   0,
 		},
diff --git a/internal/testdata/complex/complex.proto b/internal/testdata/complex/complex.proto
index 64e5c448..4e20d5a3 100644
--- a/internal/testdata/complex/complex.proto
+++ b/internal/testdata/complex/complex.proto
@@ -40,6 +40,7 @@ message Complex {
   google.protobuf.BytesValue bytes = 24;
 
   map<string,string> map = 25;
+  map<int64,string> map_int64_key = 26 [json_name = "map_int64_key"];
 }
 
 message Simple {
diff --git a/internal/testdata/complex/generate.go b/internal/testdata/complex/generate.go
new file mode 100644
index 00000000..c3cfd9fb
--- /dev/null
+++ b/internal/testdata/complex/generate.go
@@ -0,0 +1,3 @@
+package complex
+
+//go:generate protoc -I . --go_out=paths=source_relative:. ./complex.proto
diff --git a/transport/http/context_test.go b/transport/http/context_test.go
index 6cae1b9a..8cc79da0 100644
--- a/transport/http/context_test.go
+++ b/transport/http/context_test.go
@@ -100,6 +100,34 @@ func TestContextResponse(t *testing.T) {
 	}
 }
 
+func TestResponseUnwrap(t *testing.T) {
+	res := httptest.NewRecorder()
+	f := func(rw http.ResponseWriter, r *http.Request, a interface{}) error {
+		u, ok := rw.(interface {
+			Unwrap() http.ResponseWriter
+		})
+		if !ok {
+			return errors.New("can not unwrap")
+		}
+		w := u.Unwrap()
+		if !reflect.DeepEqual(w, res) {
+			return errors.New("underlying response writer not equal")
+		}
+		return nil
+	}
+
+	w := wrapper{
+		router: &Router{srv: &Server{enc: f}},
+		req:    nil,
+		res:    res,
+		w:      responseWriter{200, res},
+	}
+	err := w.Result(200, "ok")
+	if err != nil {
+		t.Errorf("expected %v, got %v", nil, err)
+	}
+}
+
 func TestContextBindQuery(t *testing.T) {
 	w := wrapper{
 		router: testRouter,