nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: zeromicro/go-zero
Pull request #1641 (2022-03-14 07:25:38)

feat: add httpc/Service for convinience


Patch:
diff --git a/rest/httpc/service.go b/rest/httpc/service.go
new file mode 100644
index 00000000..eb917391
--- /dev/null
+++ b/rest/httpc/service.go
@@ -0,0 +1,39 @@
+package httpc
+
+import (
+	"io"
+	"net/http"
+)
+
+type (
+	Service interface {
+		Do(r *http.Request, opts ...Option) (*http.Response, error)
+		Get(url string, opts ...Option) (*http.Response, error)
+		Post(url, contentType string, body io.Reader, opts ...Option) (*http.Response, error)
+	}
+
+	namedService struct {
+		name string
+		opts []Option
+	}
+)
+
+func NewService(name string, opts ...Option) Service {
+	return namedService{
+		name: name,
+		opts: opts,
+	}
+}
+
+func (s namedService) Do(r *http.Request, opts ...Option) (*http.Response, error) {
+	return Do(s.name, r, append(s.opts, opts...)...)
+}
+
+func (s namedService) Get(url string, opts ...Option) (*http.Response, error) {
+	return Get(s.name, url, append(s.opts, opts...)...)
+}
+
+func (s namedService) Post(url, contentType string, body io.Reader, opts ...Option) (
+	*http.Response, error) {
+	return Post(s.name, url, contentType, body, append(s.opts, opts...)...)
+}


Test patch:
diff --git a/rest/httpc/service_test.go b/rest/httpc/service_test.go
new file mode 100644
index 00000000..82e78bca
--- /dev/null
+++ b/rest/httpc/service_test.go
@@ -0,0 +1,40 @@
+package httpc
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+)
+
+func TestNamedService_Do(t *testing.T) {
+	svr := httptest.NewServer(http.RedirectHandler("/foo", http.StatusMovedPermanently))
+	req, err := http.NewRequest(http.MethodGet, svr.URL, nil)
+	assert.Nil(t, err)
+	service := NewService("foo")
+	_, err = service.Do(req)
+	// too many redirects
+	assert.NotNil(t, err)
+}
+
+func TestNamedService_Get(t *testing.T) {
+	svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+	}))
+	service := NewService("foo")
+	resp, err := service.Get(svr.URL, func(cli *http.Client) {
+		cli.Transport = http.DefaultTransport
+	})
+	assert.Nil(t, err)
+	assert.Equal(t, http.StatusOK, resp.StatusCode)
+}
+
+func TestNamedService_Post(t *testing.T) {
+	svr := httptest.NewServer(http.NotFoundHandler())
+	service := NewService("foo")
+	_, err := service.Post("tcp://bad request", "application/json", nil)
+	assert.NotNil(t, err)
+	resp, err := service.Post(svr.URL, "application/json", nil)
+	assert.Nil(t, err)
+	assert.Equal(t, http.StatusNotFound, resp.StatusCode)
+}
Repository: zeromicro/go-zero
Pull request #1708 (2022-03-24 13:48:29)

chore: refactor code


Patch:
diff --git a/core/mapping/unmarshaler.go b/core/mapping/unmarshaler.go
index 780b2420..a8be682c 100644
--- a/core/mapping/unmarshaler.go
+++ b/core/mapping/unmarshaler.go
@@ -448,10 +448,12 @@ func (u *Unmarshaler) fillSlice(fieldType reflect.Type, value reflect.Value, map
 	dereffedBaseType := Deref(baseType)
 	dereffedBaseKind := dereffedBaseType.Kind()
 	refValue := reflect.ValueOf(mapValue)
-	conv := reflect.MakeSlice(reflect.SliceOf(baseType), refValue.Len(), refValue.Cap())
+	if refValue.IsNil() {
+		return nil
+	}
 
-	// support for empty slice
-	if !refValue.IsNil() && refValue.Len() == 0 {
+	conv := reflect.MakeSlice(reflect.SliceOf(baseType), refValue.Len(), refValue.Cap())
+	if refValue.Len() == 0 {
 		value.Set(conv)
 		return nil
 	}


Test patch:
diff --git a/core/mapping/unmarshaler_test.go b/core/mapping/unmarshaler_test.go
index e71adca2..1b3bdcfc 100644
--- a/core/mapping/unmarshaler_test.go
+++ b/core/mapping/unmarshaler_test.go
@@ -198,6 +198,49 @@ func TestUnmarshalIntWithDefault(t *testing.T) {
 	assert.Equal(t, 1, in.Int)
 }
 
+func TestUnmarshalBoolSliceRequired(t *testing.T) {
+	type inner struct {
+		Bools []bool `key:"bools"`
+	}
+
+	var in inner
+	assert.NotNil(t, UnmarshalKey(map[string]interface{}{}, &in))
+}
+
+func TestUnmarshalBoolSliceNil(t *testing.T) {
+	type inner struct {
+		Bools []bool `key:"bools,optional"`
+	}
+
+	var in inner
+	assert.Nil(t, UnmarshalKey(map[string]interface{}{}, &in))
+	assert.Nil(t, in.Bools)
+}
+
+func TestUnmarshalBoolSliceNilExplicit(t *testing.T) {
+	type inner struct {
+		Bools []bool `key:"bools,optional"`
+	}
+
+	var in inner
+	assert.Nil(t, UnmarshalKey(map[string]interface{}{
+		"bools": nil,
+	}, &in))
+	assert.Nil(t, in.Bools)
+}
+
+func TestUnmarshalBoolSliceEmpty(t *testing.T) {
+	type inner struct {
+		Bools []bool `key:"bools,optional"`
+	}
+
+	var in inner
+	assert.Nil(t, UnmarshalKey(map[string]interface{}{
+		"bools": []bool{},
+	}, &in))
+	assert.Empty(t, in.Bools)
+}
+
 func TestUnmarshalBoolSliceWithDefault(t *testing.T) {
 	type inner struct {
 		Bools []bool `key:"bools,default=[true,false]"`
Repository: zeromicro/go-zero
Pull request #1739 (2022-04-01 13:48:56)

fix:  zrpc code generation error with --remote


Patch:
diff --git a/tools/goctl/rpc/cli/zrpc.go b/tools/goctl/rpc/cli/zrpc.go
index fa84d8ea..2550f66c 100644
--- a/tools/goctl/rpc/cli/zrpc.go
+++ b/tools/goctl/rpc/cli/zrpc.go
@@ -118,13 +118,18 @@ func removeGoctlFlag(args []string) []string {
 	for step < len(args) {
 		arg := args[step]
 		switch {
-		case arg == "--style", arg == "--home", arg == "--zrpc_out", arg == "--verbose", arg == "-v":
+		case arg == "--style", arg == "--home",
+			arg == "--zrpc_out", arg == "--verbose",
+			arg == "-v", arg == "--remote",
+			arg == "--branch":
 			step += 2
 			continue
 		case strings.HasPrefix(arg, "--style="),
 			strings.HasPrefix(arg, "--home="),
 			strings.HasPrefix(arg, "--verbose="),
 			strings.HasPrefix(arg, "-v="),
+			strings.HasPrefix(arg, "--remote="),
+			strings.HasPrefix(arg, "--branch="),
 			strings.HasPrefix(arg, "--zrpc_out="):
 			step += 1
 			continue


Test patch:
diff --git a/tools/goctl/rpc/cli/zrpc_test.go b/tools/goctl/rpc/cli/zrpc_test.go
index 051556ad..d841115e 100644
--- a/tools/goctl/rpc/cli/zrpc_test.go
+++ b/tools/goctl/rpc/cli/zrpc_test.go
@@ -83,6 +83,14 @@ func Test_RemoveGoctlFlag(t *testing.T) {
 			source:   strings.Fields(`protoc --go_opt=. --go-grpc_out=. --zrpc_out=. foo.proto`),
 			expected: "protoc --go_opt=. --go-grpc_out=. foo.proto",
 		},
+		{
+			source:   strings.Fields(`protoc --go_opt=. --go-grpc_out=. --zrpc_out=. --remote=foo --branch=bar foo.proto`),
+			expected: "protoc --go_opt=. --go-grpc_out=. foo.proto",
+		},
+		{
+			source:   strings.Fields(`protoc --go_opt=. --go-grpc_out=. --zrpc_out=. --remote foo --branch bar foo.proto`),
+			expected: "protoc --go_opt=. --go-grpc_out=. foo.proto",
+		},
 	}
 	for _, e := range testData {
 		cmd := strings.Join(removeGoctlFlag(e.source), " ")
Repository: zeromicro/go-zero
Pull request #1746 (2022-04-02 11:20:23)

feat: return original value of setbit in redis


Patch:
diff --git a/core/stores/redis/redis.go b/core/stores/redis/redis.go
index cb6cbcbd..9095d7d3 100644
--- a/core/stores/redis/redis.go
+++ b/core/stores/redis/redis.go
@@ -1404,21 +1404,28 @@ func (s *Redis) ScanCtx(ctx context.Context, cursor uint64, match string, count
 }
 
 // SetBit is the implementation of redis setbit command.
-func (s *Redis) SetBit(key string, offset int64, value int) error {
+func (s *Redis) SetBit(key string, offset int64, value int) (int, error) {
 	return s.SetBitCtx(context.Background(), key, offset, value)
 }
 
 // SetBitCtx is the implementation of redis setbit command.
-func (s *Redis) SetBitCtx(ctx context.Context, key string, offset int64, value int) error {
-	return s.brk.DoWithAcceptable(func() error {
+func (s *Redis) SetBitCtx(ctx context.Context, key string, offset int64, value int) (val int, err error) {
+	err = s.brk.DoWithAcceptable(func() error {
 		conn, err := getRedis(s)
 		if err != nil {
 			return err
 		}
 
-		_, err = conn.SetBit(ctx, key, offset, value).Result()
-		return err
+		v, err := conn.SetBit(ctx, key, offset, value).Result()
+		if err != nil {
+			return err
+		}
+
+		val = int(v)
+		return nil
 	}, acceptable)
+
+	return
 }
 
 // Sscan is the implementation of redis sscan command.


Test patch:
diff --git a/core/stores/redis/redis_test.go b/core/stores/redis/redis_test.go
index fe8aa7ca..fdf90e71 100644
--- a/core/stores/redis/redis_test.go
+++ b/core/stores/redis/redis_test.go
@@ -387,30 +387,33 @@ func TestRedis_Mget(t *testing.T) {
 
 func TestRedis_SetBit(t *testing.T) {
 	runOnRedis(t, func(client *Redis) {
-		err := New(client.Addr, badType()).SetBit("key", 1, 1)
+		_, err := New(client.Addr, badType()).SetBit("key", 1, 1)
 		assert.NotNil(t, err)
-		err = client.SetBit("key", 1, 1)
+		val, err := client.SetBit("key", 1, 1)
 		assert.Nil(t, err)
+		assert.Equal(t, 0, val)
 	})
 }
 
 func TestRedis_GetBit(t *testing.T) {
 	runOnRedis(t, func(client *Redis) {
-		err := client.SetBit("key", 2, 1)
+		val, err := client.SetBit("key", 2, 1)
 		assert.Nil(t, err)
+		assert.Equal(t, 0, val)
 		_, err = New(client.Addr, badType()).GetBit("key", 2)
 		assert.NotNil(t, err)
-		val, err := client.GetBit("key", 2)
+		v, err := client.GetBit("key", 2)
 		assert.Nil(t, err)
-		assert.Equal(t, 1, val)
+		assert.Equal(t, 1, v)
 	})
 }
 
 func TestRedis_BitCount(t *testing.T) {
 	runOnRedis(t, func(client *Redis) {
 		for i := 0; i < 11; i++ {
-			err := client.SetBit("key", int64(i), 1)
+			val, err := client.SetBit("key", int64(i), 1)
 			assert.Nil(t, err)
+			assert.Equal(t, 0, val)
 		}
 
 		_, err := New(client.Addr, badType()).BitCount("key", 0, -1)
Repository: zeromicro/go-zero
Pull request #1763 (2022-04-06 07:58:59)

add more tests


Patch:
diff --git a/tools/goctl/Makefile b/tools/goctl/Makefile
index 3f4f8336..14a725e5 100644
--- a/tools/goctl/Makefile
+++ b/tools/goctl/Makefile
@@ -1,12 +1,15 @@
 build:
 	go build -ldflags="-s -w" goctl.go
 	$(if $(shell command -v upx), upx goctl)
+
 mac:
 	GOOS=darwin go build -ldflags="-s -w" -o goctl-darwin goctl.go
 	$(if $(shell command -v upx), upx goctl-darwin)
+
 win:
 	GOOS=windows go build -ldflags="-s -w" -o goctl.exe goctl.go
 	$(if $(shell command -v upx), upx goctl.exe)
+
 linux:
 	GOOS=linux go build -ldflags="-s -w" -o goctl-linux goctl.go
 	$(if $(shell command -v upx), upx goctl-linux)


Test patch:
diff --git a/rest/handler/cryptionhandler_test.go b/rest/handler/cryptionhandler_test.go
index 2957d193..0d9fba47 100644
--- a/rest/handler/cryptionhandler_test.go
+++ b/rest/handler/cryptionhandler_test.go
@@ -5,6 +5,7 @@ import (
 	"encoding/base64"
 	"io/ioutil"
 	"log"
+	"math/rand"
 	"net/http"
 	"net/http/httptest"
 	"testing"
@@ -116,3 +117,18 @@ func TestCryptionHandler_Hijack(t *testing.T) {
 		writer.Hijack()
 	})
 }
+
+func TestCryptionHandler_ContentTooLong(t *testing.T) {
+	handler := CryptionHandler(aesKey)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+	}))
+	svr := httptest.NewServer(handler)
+	defer svr.Close()
+
+	body := make([]byte, maxBytes+1)
+	rand.Read(body)
+	req, err := http.NewRequest(http.MethodPost, svr.URL, bytes.NewReader(body))
+	assert.Nil(t, err)
+	resp, err := http.DefaultClient.Do(req)
+	assert.Nil(t, err)
+	assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
+}
Repository: zeromicro/go-zero
Pull request #1781 (2022-04-13 04:36:14)

refactor: move postgres to pg package


Patch:
diff --git a/core/collection/timingwheel.go b/core/collection/timingwheel.go
index 38953c8b..d1f1ea33 100644
--- a/core/collection/timingwheel.go
+++ b/core/collection/timingwheel.go
@@ -71,8 +71,8 @@ func NewTimingWheel(interval time.Duration, numSlots int, execute Execute) (*Tim
 	return newTimingWheelWithClock(interval, numSlots, execute, timex.NewTicker(interval))
 }
 
-func newTimingWheelWithClock(interval time.Duration, numSlots int, execute Execute, ticker timex.Ticker) (
-	*TimingWheel, error) {
+func newTimingWheelWithClock(interval time.Duration, numSlots int, execute Execute,
+	ticker timex.Ticker) (*TimingWheel, error) {
 	tw := &TimingWheel{
 		interval:      interval,
 		ticker:        ticker,
diff --git a/core/stores/pg/postgresql.go b/core/stores/pg/postgresql.go
new file mode 100644
index 00000000..f813836f
--- /dev/null
+++ b/core/stores/pg/postgresql.go
@@ -0,0 +1,14 @@
+package pg
+
+import (
+	// imports the driver, don't remove this comment, golint requires.
+	_ "github.com/lib/pq"
+	"github.com/zeromicro/go-zero/core/stores/sqlx"
+)
+
+const postgresDriverName = "postgres"
+
+// New returns a postgres connection.
+func New(datasource string, opts ...sqlx.SqlOption) sqlx.SqlConn {
+	return sqlx.NewSqlConn(postgresDriverName, datasource, opts...)
+}
diff --git a/core/stores/postgres/postgresql.go b/core/stores/postgres/postgresql.go
index 48d6e3a0..4aee1933 100644
--- a/core/stores/postgres/postgresql.go
+++ b/core/stores/postgres/postgresql.go
@@ -1,14 +1,7 @@
 package postgres
 
-import (
-	// imports the driver, don't remove this comment, golint requires.
-	_ "github.com/lib/pq"
-	"github.com/zeromicro/go-zero/core/stores/sqlx"
-)
+import "github.com/zeromicro/go-zero/core/stores/pg"
 
-const postgresDriverName = "postgres"
-
-// New returns a postgres connection.
-func New(datasource string, opts ...sqlx.SqlOption) sqlx.SqlConn {
-	return sqlx.NewSqlConn(postgresDriverName, datasource, opts...)
-}
+// New creates a new postgresql store.
+// Deprecated: use pg.New instead.
+var New = pg.New


Test patch:
diff --git a/core/stores/pg/postgresql_test.go b/core/stores/pg/postgresql_test.go
new file mode 100644
index 00000000..15628ec9
--- /dev/null
+++ b/core/stores/pg/postgresql_test.go
@@ -0,0 +1,11 @@
+package pg
+
+import (
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+)
+
+func TestPostgreSql(t *testing.T) {
+	assert.NotNil(t, New("postgre"))
+}
Repository: zeromicro/go-zero
Pull request #1796 (2022-04-17 03:52:11)

revert postgres package refactor


Patch:
diff --git a/core/collection/timingwheel.go b/core/collection/timingwheel.go
index d1f1ea33..327b1764 100644
--- a/core/collection/timingwheel.go
+++ b/core/collection/timingwheel.go
@@ -65,7 +65,8 @@ type (
 // NewTimingWheel returns a TimingWheel.
 func NewTimingWheel(interval time.Duration, numSlots int, execute Execute) (*TimingWheel, error) {
 	if interval <= 0 || numSlots <= 0 || execute == nil {
-		return nil, fmt.Errorf("interval: %v, slots: %d, execute: %p", interval, numSlots, execute)
+		return nil, fmt.Errorf("interval: %v, slots: %d, execute: %p",
+			interval, numSlots, execute)
 	}
 
 	return newTimingWheelWithClock(interval, numSlots, execute, timex.NewTicker(interval))
diff --git a/core/stores/pg/postgresql.go b/core/stores/pg/postgresql.go
deleted file mode 100644
index f813836f..00000000
--- a/core/stores/pg/postgresql.go
+++ /dev/null
@@ -1,14 +0,0 @@
-package pg
-
-import (
-	// imports the driver, don't remove this comment, golint requires.
-	_ "github.com/lib/pq"
-	"github.com/zeromicro/go-zero/core/stores/sqlx"
-)
-
-const postgresDriverName = "postgres"
-
-// New returns a postgres connection.
-func New(datasource string, opts ...sqlx.SqlOption) sqlx.SqlConn {
-	return sqlx.NewSqlConn(postgresDriverName, datasource, opts...)
-}
diff --git a/core/stores/postgres/postgresql.go b/core/stores/postgres/postgresql.go
index 4aee1933..48d6e3a0 100644
--- a/core/stores/postgres/postgresql.go
+++ b/core/stores/postgres/postgresql.go
@@ -1,7 +1,14 @@
 package postgres
 
-import "github.com/zeromicro/go-zero/core/stores/pg"
+import (
+	// imports the driver, don't remove this comment, golint requires.
+	_ "github.com/lib/pq"
+	"github.com/zeromicro/go-zero/core/stores/sqlx"
+)
 
-// New creates a new postgresql store.
-// Deprecated: use pg.New instead.
-var New = pg.New
+const postgresDriverName = "postgres"
+
+// New returns a postgres connection.
+func New(datasource string, opts ...sqlx.SqlOption) sqlx.SqlConn {
+	return sqlx.NewSqlConn(postgresDriverName, datasource, opts...)
+}


Test patch:
diff --git a/core/stores/pg/postgresql_test.go b/core/stores/pg/postgresql_test.go
deleted file mode 100644
index 15628ec9..00000000
--- a/core/stores/pg/postgresql_test.go
+++ /dev/null
@@ -1,11 +0,0 @@
-package pg
-
-import (
-	"testing"
-
-	"github.com/stretchr/testify/assert"
-)
-
-func TestPostgreSql(t *testing.T) {
-	assert.NotNil(t, New("postgre"))
-}
Repository: zeromicro/go-zero
Pull request #1802 (2022-04-18 11:22:24)

fix: ignore timeout on websocket


Patch:
diff --git a/rest/handler/timeouthandler.go b/rest/handler/timeouthandler.go
index 672f44b6..ca4b4a49 100644
--- a/rest/handler/timeouthandler.go
+++ b/rest/handler/timeouthandler.go
@@ -20,6 +20,8 @@ import (
 const (
 	statusClientClosedRequest = 499
 	reason                    = "Request Timeout"
+	headerUpgrade             = "Upgrade"
+	valueWebsocket            = "websocket"
 )
 
 // TimeoutHandler returns the handler with given timeout.
@@ -52,6 +54,11 @@ func (h *timeoutHandler) errorBody() string {
 }
 
 func (h *timeoutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+	if r.Header.Get(headerUpgrade) == valueWebsocket {
+		h.handler.ServeHTTP(w, r)
+		return
+	}
+
 	ctx, cancelCtx := context.WithTimeout(r.Context(), h.dt)
 	defer cancelCtx()
 


Test patch:
diff --git a/rest/handler/timeouthandler_test.go b/rest/handler/timeouthandler_test.go
index 74c70687..d4d2ad20 100644
--- a/rest/handler/timeouthandler_test.go
+++ b/rest/handler/timeouthandler_test.go
@@ -79,6 +79,19 @@ func TestTimeoutPanic(t *testing.T) {
 	})
 }
 
+func TestTimeoutWebsocket(t *testing.T) {
+	timeoutHandler := TimeoutHandler(time.Millisecond)
+	handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		time.Sleep(time.Millisecond * 10)
+	}))
+
+	req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
+	req.Header.Set(headerUpgrade, valueWebsocket)
+	resp := httptest.NewRecorder()
+	handler.ServeHTTP(resp, req)
+	assert.Equal(t, http.StatusOK, resp.Code)
+}
+
 func TestTimeoutWroteHeaderTwice(t *testing.T) {
 	timeoutHandler := TimeoutHandler(time.Minute)
 	handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Repository: zeromicro/go-zero
Pull request #1827 (2022-04-25 13:07:43)

feat: support sub domain for cors


Patch:
diff --git a/rest/internal/cors/handlers.go b/rest/internal/cors/handlers.go
index 7bb3f077..e2a64b74 100644
--- a/rest/internal/cors/handlers.go
+++ b/rest/internal/cors/handlers.go
@@ -2,6 +2,7 @@ package cors
 
 import (
 	"net/http"
+	"strings"
 
 	"github.com/zeromicro/go-zero/rest/internal/response"
 )
@@ -81,7 +82,7 @@ func isOriginAllowed(allows []string, origin string) bool {
 			return true
 		}
 
-		if o == origin {
+		if strings.HasSuffix(origin, o) {
 			return true
 		}
 	}


Test patch:
diff --git a/rest/internal/cors/handlers_test.go b/rest/internal/cors/handlers_test.go
index dea7bb4e..4a398ba5 100644
--- a/rest/internal/cors/handlers_test.go
+++ b/rest/internal/cors/handlers_test.go
@@ -31,6 +31,12 @@ func TestCorsHandlerWithOrigins(t *testing.T) {
 			reqOrigin: "http://local",
 			expect:    "http://local",
 		},
+		{
+			name:      "allow sub origins",
+			origins:   []string{"local", "remote"},
+			reqOrigin: "sub.local",
+			expect:    "sub.local",
+		},
 		{
 			name:      "allow all origins",
 			reqOrigin: "http://local",
Repository: zeromicro/go-zero
Pull request #1882 (2022-05-09 11:53:38)

fix:tools/goctl/rpc/generator/template_test.go file has wrong parameters
remove the nil parameters


Patch:
diff --git a/readme-cn.md b/readme-cn.md
index fb984cc5..0f31a755 100644
--- a/readme-cn.md
+++ b/readme-cn.md
@@ -267,6 +267,8 @@ go-zero 已被许多公司用于生产部署，接入场景如在线教育、电
 >59. 费芮网络
 >60. 51CTO
 >61. 聿旌科技
+>62. 山东胜软科技股份有限公司
+>63. 上海芯果科技有限公司(好特卖)
 
 如果贵公司也已使用 go-zero，欢迎在 [登记地址](https://github.com/zeromicro/go-zero/issues/602) 登记，仅仅为了推广，不做其它用途。
 


Test patch:
diff --git a/tools/goctl/rpc/generator/template_test.go b/tools/goctl/rpc/generator/template_test.go
index 75a74a72..7850ee60 100644
--- a/tools/goctl/rpc/generator/template_test.go
+++ b/tools/goctl/rpc/generator/template_test.go
@@ -12,13 +12,13 @@ import (
 
 func TestGenTemplates(t *testing.T) {
 	_ = Clean()
-	err := GenTemplates(nil)
+	err := GenTemplates()
 	assert.Nil(t, err)
 }
 
 func TestRevertTemplate(t *testing.T) {
 	_ = Clean()
-	err := GenTemplates(nil)
+	err := GenTemplates()
 	assert.Nil(t, err)
 	fp, err := pathx.GetTemplateDir(category)
 	if err != nil {
@@ -59,7 +59,7 @@ func TestRevertTemplate(t *testing.T) {
 
 func TestClean(t *testing.T) {
 	_ = Clean()
-	err := GenTemplates(nil)
+	err := GenTemplates()
 	assert.Nil(t, err)
 	fp, err := pathx.GetTemplateDir(category)
 	if err != nil {
@@ -78,7 +78,7 @@ func TestClean(t *testing.T) {
 
 func TestUpdate(t *testing.T) {
 	_ = Clean()
-	err := GenTemplates(nil)
+	err := GenTemplates()
 	assert.Nil(t, err)
 	fp, err := pathx.GetTemplateDir(category)
 	if err != nil {
Repository: zeromicro/go-zero
Pull request #1959 (2022-06-03 02:32:00)

chore: refactoring mapping string to slice


Patch:
diff --git a/core/mapping/unmarshaler.go b/core/mapping/unmarshaler.go
index 56e58839..a633453a 100644
--- a/core/mapping/unmarshaler.go
+++ b/core/mapping/unmarshaler.go
@@ -496,17 +496,20 @@ func (u *Unmarshaler) fillSlice(fieldType reflect.Type, value reflect.Value, map
 	return nil
 }
 
-func (u *Unmarshaler) fillSliceFromString(fieldType reflect.Type, value reflect.Value, mapValue interface{}) error {
+func (u *Unmarshaler) fillSliceFromString(fieldType reflect.Type, value reflect.Value,
+	mapValue interface{}) error {
 	var slice []interface{}
 	switch v := mapValue.(type) {
-	case json.Number:
+	case fmt.Stringer:
 		if err := jsonx.UnmarshalFromString(v.String(), &slice); err != nil {
 			return err
 		}
-	default:
-		if err := jsonx.UnmarshalFromString(mapValue.(string), &slice); err != nil {
+	case string:
+		if err := jsonx.UnmarshalFromString(v, &slice); err != nil {
 			return err
 		}
+	default:
+		return errUnsupportedType
 	}
 
 	baseFieldType := Deref(fieldType.Elem())


Test patch:
diff --git a/core/mapping/unmarshaler_test.go b/core/mapping/unmarshaler_test.go
index f3b037f0..da042490 100644
--- a/core/mapping/unmarshaler_test.go
+++ b/core/mapping/unmarshaler_test.go
@@ -2777,6 +2777,36 @@ func TestUnmarshalJsonReaderComplex(t *testing.T) {
 	assert.Equal(t, "txt", req.Txt)
 }
 
+func TestUnmarshalJsonReaderArrayBool(t *testing.T) {
+	payload := `{"id": false}`
+	var res struct {
+		ID []string `json:"id"`
+	}
+	reader := strings.NewReader(payload)
+	err := UnmarshalJsonReader(reader, &res)
+	assert.NotNil(t, err)
+}
+
+func TestUnmarshalJsonReaderArrayInt(t *testing.T) {
+	payload := `{"id": 123}`
+	var res struct {
+		ID []string `json:"id"`
+	}
+	reader := strings.NewReader(payload)
+	err := UnmarshalJsonReader(reader, &res)
+	assert.NotNil(t, err)
+}
+
+func TestUnmarshalJsonReaderArrayString(t *testing.T) {
+	payload := `{"id": "123"}`
+	var res struct {
+		ID []string `json:"id"`
+	}
+	reader := strings.NewReader(payload)
+	err := UnmarshalJsonReader(reader, &res)
+	assert.NotNil(t, err)
+}
+
 func BenchmarkDefaultValue(b *testing.B) {
 	for i := 0; i < b.N; i++ {
 		var a struct {
@@ -2789,14 +2819,3 @@ func BenchmarkDefaultValue(b *testing.B) {
 		}
 	}
 }
-
-func TestUnmarshalJsonReaderArray(t *testing.T) {
-	payload := "{\"id\": 123}"
-	var res struct {
-		ID []string   `json:"id"`
-	}
-	reader := strings.NewReader(payload)
-	err := UnmarshalJsonReader(reader, &res)
-	assert.Nil(t, err)
-	assert.Equal(t, 1, len(res.ID))
-}