Skip to content

Commit a134948

Browse files
authored
Merge branch 'master' into feat/goctl_api_wrapCodeMsg
2 parents cf15a94 + c9ff6a1 commit a134948

File tree

9 files changed

+134
-31
lines changed

9 files changed

+134
-31
lines changed

core/logx/fields.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,11 @@ import (
77
)
88

99
var (
10-
fieldsContextKey contextKey
1110
globalFields atomic.Value
1211
globalFieldsLock sync.Mutex
1312
)
1413

15-
type contextKey struct{}
14+
type fieldsKey struct{}
1615

1716
// AddGlobalFields adds global fields.
1817
func AddGlobalFields(fields ...LogField) {
@@ -29,16 +28,16 @@ func AddGlobalFields(fields ...LogField) {
2928

3029
// ContextWithFields returns a new context with the given fields.
3130
func ContextWithFields(ctx context.Context, fields ...LogField) context.Context {
32-
if val := ctx.Value(fieldsContextKey); val != nil {
31+
if val := ctx.Value(fieldsKey{}); val != nil {
3332
if arr, ok := val.([]LogField); ok {
3433
allFields := make([]LogField, 0, len(arr)+len(fields))
3534
allFields = append(allFields, arr...)
3635
allFields = append(allFields, fields...)
37-
return context.WithValue(ctx, fieldsContextKey, allFields)
36+
return context.WithValue(ctx, fieldsKey{}, allFields)
3837
}
3938
}
4039

41-
return context.WithValue(ctx, fieldsContextKey, fields)
40+
return context.WithValue(ctx, fieldsKey{}, fields)
4241
}
4342

4443
// WithFields returns a new logger with the given fields.

core/logx/fields_test.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ func TestAddGlobalFields(t *testing.T) {
3434

3535
func TestContextWithFields(t *testing.T) {
3636
ctx := ContextWithFields(context.Background(), Field("a", 1), Field("b", 2))
37-
vals := ctx.Value(fieldsContextKey)
37+
vals := ctx.Value(fieldsKey{})
3838
assert.NotNil(t, vals)
3939
fields, ok := vals.([]LogField)
4040
assert.True(t, ok)
@@ -43,7 +43,7 @@ func TestContextWithFields(t *testing.T) {
4343

4444
func TestWithFields(t *testing.T) {
4545
ctx := WithFields(context.Background(), Field("a", 1), Field("b", 2))
46-
vals := ctx.Value(fieldsContextKey)
46+
vals := ctx.Value(fieldsKey{})
4747
assert.NotNil(t, vals)
4848
fields, ok := vals.([]LogField)
4949
assert.True(t, ok)
@@ -55,7 +55,7 @@ func TestWithFieldsAppend(t *testing.T) {
5555
ctx := context.WithValue(context.Background(), dummyKey, "dummy")
5656
ctx = ContextWithFields(ctx, Field("a", 1), Field("b", 2))
5757
ctx = ContextWithFields(ctx, Field("c", 3), Field("d", 4))
58-
vals := ctx.Value(fieldsContextKey)
58+
vals := ctx.Value(fieldsKey{})
5959
assert.NotNil(t, vals)
6060
fields, ok := vals.([]LogField)
6161
assert.True(t, ok)
@@ -80,8 +80,8 @@ func TestWithFieldsAppendCopy(t *testing.T) {
8080
ctxa := ContextWithFields(ctx, af)
8181
ctxb := ContextWithFields(ctx, bf)
8282

83-
assert.EqualValues(t, af, ctxa.Value(fieldsContextKey).([]LogField)[count])
84-
assert.EqualValues(t, bf, ctxb.Value(fieldsContextKey).([]LogField)[count])
83+
assert.EqualValues(t, af, ctxa.Value(fieldsKey{}).([]LogField)[count])
84+
assert.EqualValues(t, bf, ctxb.Value(fieldsKey{}).([]LogField)[count])
8585
}
8686

8787
func BenchmarkAtomicValue(b *testing.B) {

core/logx/richlogger.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ func (l *richLogger) buildFields(fields ...LogField) []LogField {
224224
fields = append(fields, Field(spanKey, spanID))
225225
}
226226

227-
val := l.ctx.Value(fieldsContextKey)
227+
val := l.ctx.Value(fieldsKey{})
228228
if val != nil {
229229
if arr, ok := val.([]LogField); ok {
230230
fields = append(fields, arr...)

core/stores/sqlx/rwstrategy.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,21 +27,21 @@ const (
2727
notSpecifiedMode readWriteMode = ""
2828
)
2929

30-
var readWriteModeKey struct{}
30+
type readWriteModeKey struct{}
3131

3232
// WithReadPrimary sets the context to read-primary mode.
3333
func WithReadPrimary(ctx context.Context) context.Context {
34-
return context.WithValue(ctx, readWriteModeKey, readPrimaryMode)
34+
return context.WithValue(ctx, readWriteModeKey{}, readPrimaryMode)
3535
}
3636

3737
// WithReadReplica sets the context to read-replica mode.
3838
func WithReadReplica(ctx context.Context) context.Context {
39-
return context.WithValue(ctx, readWriteModeKey, readReplicaMode)
39+
return context.WithValue(ctx, readWriteModeKey{}, readReplicaMode)
4040
}
4141

4242
// WithWrite sets the context to write mode, indicating that the operation is a write operation.
4343
func WithWrite(ctx context.Context) context.Context {
44-
return context.WithValue(ctx, readWriteModeKey, writeMode)
44+
return context.WithValue(ctx, readWriteModeKey{}, writeMode)
4545
}
4646

4747
type readWriteMode string
@@ -51,7 +51,7 @@ func (m readWriteMode) isValid() bool {
5151
}
5252

5353
func getReadWriteMode(ctx context.Context) readWriteMode {
54-
if mode := ctx.Value(readWriteModeKey); mode != nil {
54+
if mode := ctx.Value(readWriteModeKey{}); mode != nil {
5555
if v, ok := mode.(readWriteMode); ok && v.isValid() {
5656
return v
5757
}

core/stores/sqlx/rwstrategy_test.go

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -57,45 +57,45 @@ func TestWithReadMode(t *testing.T) {
5757
ctx := context.Background()
5858
readPrimaryCtx := WithReadPrimary(ctx)
5959

60-
val := readPrimaryCtx.Value(readWriteModeKey)
60+
val := readPrimaryCtx.Value(readWriteModeKey{})
6161
assert.Equal(t, readPrimaryMode, val)
6262

6363
readReplicaCtx := WithReadReplica(ctx)
64-
val = readReplicaCtx.Value(readWriteModeKey)
64+
val = readReplicaCtx.Value(readWriteModeKey{})
6565
assert.Equal(t, readReplicaMode, val)
6666
}
6767

6868
func TestWithWriteMode(t *testing.T) {
6969
ctx := context.Background()
7070
writeCtx := WithWrite(ctx)
7171

72-
val := writeCtx.Value(readWriteModeKey)
72+
val := writeCtx.Value(readWriteModeKey{})
7373
assert.Equal(t, writeMode, val)
7474
}
7575

7676
func TestGetReadWriteMode(t *testing.T) {
7777
t.Run("valid read-primary mode", func(t *testing.T) {
78-
ctx := context.WithValue(context.Background(), readWriteModeKey, readPrimaryMode)
78+
ctx := context.WithValue(context.Background(), readWriteModeKey{}, readPrimaryMode)
7979
assert.Equal(t, readPrimaryMode, getReadWriteMode(ctx))
8080
})
8181

8282
t.Run("valid read-replica mode", func(t *testing.T) {
83-
ctx := context.WithValue(context.Background(), readWriteModeKey, readReplicaMode)
83+
ctx := context.WithValue(context.Background(), readWriteModeKey{}, readReplicaMode)
8484
assert.Equal(t, readReplicaMode, getReadWriteMode(ctx))
8585
})
8686

8787
t.Run("valid write mode", func(t *testing.T) {
88-
ctx := context.WithValue(context.Background(), readWriteModeKey, writeMode)
88+
ctx := context.WithValue(context.Background(), readWriteModeKey{}, writeMode)
8989
assert.Equal(t, writeMode, getReadWriteMode(ctx))
9090
})
9191

9292
t.Run("invalid mode value (wrong type)", func(t *testing.T) {
93-
ctx := context.WithValue(context.Background(), readWriteModeKey, "not-a-mode")
93+
ctx := context.WithValue(context.Background(), readWriteModeKey{}, "not-a-mode")
9494
assert.Equal(t, notSpecifiedMode, getReadWriteMode(ctx))
9595
})
9696

9797
t.Run("invalid mode value (wrong value)", func(t *testing.T) {
98-
ctx := context.WithValue(context.Background(), readWriteModeKey, readWriteMode("delete"))
98+
ctx := context.WithValue(context.Background(), readWriteModeKey{}, readWriteMode("delete"))
9999
assert.Equal(t, notSpecifiedMode, getReadWriteMode(ctx))
100100
})
101101

@@ -107,22 +107,22 @@ func TestGetReadWriteMode(t *testing.T) {
107107

108108
func TestUsePrimary(t *testing.T) {
109109
t.Run("context with read-replica mode", func(t *testing.T) {
110-
ctx := context.WithValue(context.Background(), readWriteModeKey, readReplicaMode)
110+
ctx := context.WithValue(context.Background(), readWriteModeKey{}, readReplicaMode)
111111
assert.False(t, usePrimary(ctx))
112112
})
113113

114114
t.Run("context with read-primary mode", func(t *testing.T) {
115-
ctx := context.WithValue(context.Background(), readWriteModeKey, readPrimaryMode)
115+
ctx := context.WithValue(context.Background(), readWriteModeKey{}, readPrimaryMode)
116116
assert.True(t, usePrimary(ctx))
117117
})
118118

119119
t.Run("context with write mode", func(t *testing.T) {
120-
ctx := context.WithValue(context.Background(), readWriteModeKey, writeMode)
120+
ctx := context.WithValue(context.Background(), readWriteModeKey{}, writeMode)
121121
assert.True(t, usePrimary(ctx))
122122
})
123123

124124
t.Run("context with invalid mode", func(t *testing.T) {
125-
ctx := context.WithValue(context.Background(), readWriteModeKey, readWriteMode("invalid"))
125+
ctx := context.WithValue(context.Background(), readWriteModeKey{}, readWriteMode("invalid"))
126126
assert.True(t, usePrimary(ctx))
127127
})
128128

@@ -137,6 +137,6 @@ func TestWithModeTwice(t *testing.T) {
137137
ctx = WithReadPrimary(ctx)
138138
writeCtx := WithWrite(ctx)
139139

140-
val := writeCtx.Value(readWriteModeKey)
140+
val := writeCtx.Value(readWriteModeKey{})
141141
assert.Equal(t, writeMode, val)
142142
}

rest/server.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,16 @@ func (s *Server) Use(middleware Middleware) {
119119
s.ngin.use(middleware)
120120
}
121121

122+
// build builds the Server and binds the routes to the router.
123+
func (s *Server) build() error {
124+
return s.ngin.bindRoutes(s.router)
125+
}
126+
127+
// serve serves the HTTP requests using the Server's router.
128+
func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
129+
s.router.ServeHTTP(w, r)
130+
}
131+
122132
// ToMiddleware converts the given handler to a Middleware.
123133
func ToMiddleware(handler func(next http.Handler) http.Handler) Middleware {
124134
return func(handle http.HandlerFunc) http.HandlerFunc {

rest/server_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -819,6 +819,6 @@ func TestServerEmbedFileSystem(t *testing.T) {
819819
// serve(server, w, r)
820820
// // verify the response
821821
func serve(s *Server, w http.ResponseWriter, r *http.Request) {
822-
s.ngin.bindRoutes(s.router)
823-
s.router.ServeHTTP(w, r)
822+
_ = s.build()
823+
s.serve(w, r)
824824
}

rest/serverless.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package rest
2+
3+
import "net/http"
4+
5+
// Serverless is a wrapper around Server that allows it to be used in serverless environments.
6+
type Serverless struct {
7+
server *Server
8+
}
9+
10+
// NewServerless creates a new Serverless instance from the provided Server.
11+
func NewServerless(server *Server) (*Serverless, error) {
12+
// Ensure the server is built before using it in a serverless context.
13+
// Why not call server.build() when serving requests,
14+
// is because we need to ensure fail fast behavior.
15+
if err := server.build(); err != nil {
16+
return nil, err
17+
}
18+
19+
return &Serverless{
20+
server: server,
21+
}, nil
22+
}
23+
24+
// Serve handles HTTP requests by delegating them to the underlying Server instance.
25+
func (s *Serverless) Serve(w http.ResponseWriter, r *http.Request) {
26+
s.server.serve(w, r)
27+
}

rest/serverless_test.go

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package rest
2+
3+
import (
4+
"net/http"
5+
"net/http/httptest"
6+
"testing"
7+
8+
"github.com/stretchr/testify/assert"
9+
"github.com/zeromicro/go-zero/core/conf"
10+
"github.com/zeromicro/go-zero/core/logx/logtest"
11+
)
12+
13+
func TestNewServerless(t *testing.T) {
14+
logtest.Discard(t)
15+
16+
const configYaml = `
17+
Name: foo
18+
Host: localhost
19+
Port: 0
20+
`
21+
var cnf RestConf
22+
assert.Nil(t, conf.LoadFromYamlBytes([]byte(configYaml), &cnf))
23+
24+
svr, err := NewServer(cnf)
25+
assert.NoError(t, err)
26+
27+
svr.AddRoute(Route{
28+
Method: http.MethodGet,
29+
Path: "/",
30+
Handler: func(w http.ResponseWriter, r *http.Request) {
31+
w.Write([]byte("Hello World"))
32+
},
33+
})
34+
35+
serverless, err := NewServerless(svr)
36+
assert.NoError(t, err)
37+
38+
w := httptest.NewRecorder()
39+
r := httptest.NewRequest(http.MethodGet, "/", nil)
40+
serverless.Serve(w, r)
41+
assert.Equal(t, http.StatusOK, w.Code)
42+
assert.Equal(t, "Hello World", w.Body.String())
43+
}
44+
45+
func TestNewServerlessWithError(t *testing.T) {
46+
logtest.Discard(t)
47+
48+
const configYaml = `
49+
Name: foo
50+
Host: localhost
51+
Port: 0
52+
`
53+
var cnf RestConf
54+
assert.Nil(t, conf.LoadFromYamlBytes([]byte(configYaml), &cnf))
55+
56+
svr, err := NewServer(cnf)
57+
assert.NoError(t, err)
58+
59+
svr.AddRoute(Route{
60+
Method: http.MethodGet,
61+
Path: "notstartwith/",
62+
Handler: nil,
63+
})
64+
65+
_, err = NewServerless(svr)
66+
assert.Error(t, err)
67+
}

0 commit comments

Comments
 (0)