repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/syncx/resourcemanager_test.go
core/syncx/resourcemanager_test.go
package syncx import ( "errors" "io" "testing" "github.com/stretchr/testify/assert" ) type dummyResource struct { age int } func (dr *dummyResource) Close() error { return errors.New("close") } func TestResourceManager_GetResource(t *testing.T) { manager := NewResourceManager() defer manager.Close() var age int for i := 0; i < 10; i++ { val, err := manager.GetResource("key", func() (io.Closer, error) { age++ return &dummyResource{ age: age, }, nil }) assert.Nil(t, err) assert.Equal(t, 1, val.(*dummyResource).age) } } func TestResourceManager_GetResourceError(t *testing.T) { manager := NewResourceManager() defer manager.Close() for i := 0; i < 10; i++ { _, err := manager.GetResource("key", func() (io.Closer, error) { return nil, errors.New("fail") }) assert.NotNil(t, err) } } func TestResourceManager_Close(t *testing.T) { manager := NewResourceManager() defer manager.Close() for i := 0; i < 10; i++ { _, err := manager.GetResource("key", func() (io.Closer, error) { return nil, errors.New("fail") }) assert.NotNil(t, err) } if assert.NoError(t, manager.Close()) { assert.Equal(t, 0, len(manager.resources)) } } func TestResourceManager_UseAfterClose(t *testing.T) { manager := NewResourceManager() defer manager.Close() _, err := manager.GetResource("key", func() (io.Closer, error) { return nil, errors.New("fail") }) assert.NotNil(t, err) if assert.NoError(t, manager.Close()) { _, err = manager.GetResource("key", func() (io.Closer, error) { return nil, errors.New("fail") }) assert.NotNil(t, err) assert.Panics(t, func() { _, err = manager.GetResource("key", func() (io.Closer, error) { return &dummyResource{age: 123}, nil }) }) } } func TestResourceManager_Inject(t *testing.T) { manager := NewResourceManager() defer manager.Close() manager.Inject("key", &dummyResource{ age: 10, }) val, err := manager.GetResource("key", func() (io.Closer, error) { return nil, nil }) assert.Nil(t, err) assert.Equal(t, 10, val.(*dummyResource).age) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/syncx/immutableresource_test.go
core/syncx/immutableresource_test.go
package syncx import ( "errors" "sync" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" ) func TestImmutableResource(t *testing.T) { var count int r := NewImmutableResource(func() (any, error) { count++ return "hello", nil }) res, err := r.Get() assert.Equal(t, "hello", res) assert.Equal(t, 1, count) assert.Nil(t, err) // again res, err = r.Get() assert.Equal(t, "hello", res) assert.Equal(t, 1, count) assert.Nil(t, err) } func TestImmutableResourceError(t *testing.T) { var count int r := NewImmutableResource(func() (any, error) { count++ return nil, errors.New("any") }) res, err := r.Get() assert.Nil(t, res) assert.NotNil(t, err) assert.Equal(t, "any", err.Error()) assert.Equal(t, 1, count) // again res, err = r.Get() assert.Nil(t, res) assert.NotNil(t, err) assert.Equal(t, "any", err.Error()) assert.Equal(t, 1, count) r.refreshInterval = 0 time.Sleep(time.Millisecond) res, err = r.Get() assert.Nil(t, res) assert.NotNil(t, err) assert.Equal(t, "any", err.Error()) assert.Equal(t, 2, count) } // It's hard to test more than one goroutine fetching the resource at the same time, // because it's difficult to make more than one goroutine to pass the first read lock // and wait another to pass the read lock before it gets the write lock. func TestImmutableResourceConcurrent(t *testing.T) { const message = "hello" var count int32 ready := make(chan struct{}) r := NewImmutableResource(func() (any, error) { atomic.AddInt32(&count, 1) close(ready) // signal that fetch started time.Sleep(10 * time.Millisecond) // simulate slow fetch return message, nil }) const goroutines = 10 var wg sync.WaitGroup results := make([]any, goroutines) errs := make([]error, goroutines) wg.Add(goroutines) for i := 0; i < goroutines; i++ { go func(idx int) { defer wg.Done() res, err := r.Get() results[idx] = res errs[idx] = err }(i) } // wait for fetch to start <-ready wg.Wait() // fetch should only be called once despite concurrent access assert.Equal(t, int32(1), atomic.LoadInt32(&count)) // all goroutines should eventually get the same result for i := 0; i < goroutines; i++ { assert.Nil(t, errs[i]) assert.Equal(t, message, results[i]) } } func TestImmutableResourceErrorRefreshAlways(t *testing.T) { var count int r := NewImmutableResource(func() (any, error) { count++ return nil, errors.New("any") }, WithRefreshIntervalOnFailure(0)) res, err := r.Get() assert.Nil(t, res) assert.NotNil(t, err) assert.Equal(t, "any", err.Error()) assert.Equal(t, 1, count) // again res, err = r.Get() assert.Nil(t, res) assert.NotNil(t, err) assert.Equal(t, "any", err.Error()) assert.Equal(t, 2, count) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/syncx/barrier.go
core/syncx/barrier.go
package syncx import "sync" // A Barrier is used to facility the barrier on a resource. type Barrier struct { lock sync.Mutex } // Guard guards the given fn on the resource. func (b *Barrier) Guard(fn func()) { Guard(&b.lock, fn) } // Guard guards the given fn with lock. func Guard(lock sync.Locker, fn func()) { lock.Lock() defer lock.Unlock() fn() }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/syncx/spinlock_test.go
core/syncx/spinlock_test.go
package syncx import ( "runtime" "sync" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/lang" ) func TestTryLock(t *testing.T) { var lock SpinLock assert.True(t, lock.TryLock()) assert.False(t, lock.TryLock()) lock.Unlock() assert.True(t, lock.TryLock()) } func TestSpinLock(t *testing.T) { var lock SpinLock lock.Lock() assert.False(t, lock.TryLock()) lock.Unlock() assert.True(t, lock.TryLock()) } func TestSpinLockRace(t *testing.T) { var lock SpinLock lock.Lock() var wait sync.WaitGroup wait.Add(1) go func() { wait.Done() }() time.Sleep(time.Millisecond * 100) lock.Unlock() wait.Wait() assert.True(t, lock.TryLock()) } func TestSpinLock_TryLock(t *testing.T) { var lock SpinLock var count int32 var wait sync.WaitGroup wait.Add(2) sig := make(chan lang.PlaceholderType) go func() { lock.TryLock() sig <- lang.Placeholder atomic.AddInt32(&count, 1) runtime.Gosched() lock.Unlock() wait.Done() }() go func() { <-sig lock.Lock() atomic.AddInt32(&count, 1) lock.Unlock() wait.Done() }() wait.Wait() assert.Equal(t, int32(2), atomic.LoadInt32(&count)) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/syncx/managedresource.go
core/syncx/managedresource.go
package syncx import "sync" // A ManagedResource is used to manage a resource that might be broken and refetched, like a connection. type ManagedResource struct { resource any lock sync.RWMutex generate func() any equals func(a, b any) bool } // NewManagedResource returns a ManagedResource. func NewManagedResource(generate func() any, equals func(a, b any) bool) *ManagedResource { return &ManagedResource{ generate: generate, equals: equals, } } // MarkBroken marks the resource broken. func (mr *ManagedResource) MarkBroken(resource any) { mr.lock.Lock() defer mr.lock.Unlock() if mr.equals(mr.resource, resource) { mr.resource = nil } } // Take takes the resource, if not loaded, generates it. func (mr *ManagedResource) Take() any { mr.lock.RLock() resource := mr.resource mr.lock.RUnlock() if resource != nil { return resource } mr.lock.Lock() defer mr.lock.Unlock() // maybe another Take() call already generated the resource. if mr.resource == nil { mr.resource = mr.generate() } return mr.resource }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/syncx/atomicbool.go
core/syncx/atomicbool.go
package syncx import "sync/atomic" // An AtomicBool is an atomic implementation for boolean values. type AtomicBool uint32 // NewAtomicBool returns an AtomicBool. func NewAtomicBool() *AtomicBool { return new(AtomicBool) } // ForAtomicBool returns an AtomicBool with given val. func ForAtomicBool(val bool) *AtomicBool { b := NewAtomicBool() b.Set(val) return b } // CompareAndSwap compares current value with given old, if equals, set to given val. func (b *AtomicBool) CompareAndSwap(old, val bool) bool { var ov, nv uint32 if old { ov = 1 } if val { nv = 1 } return atomic.CompareAndSwapUint32((*uint32)(b), ov, nv) } // Set sets the value to v. func (b *AtomicBool) Set(v bool) { if v { atomic.StoreUint32((*uint32)(b), 1) } else { atomic.StoreUint32((*uint32)(b), 0) } } // True returns true if current value is true. func (b *AtomicBool) True() bool { return atomic.LoadUint32((*uint32)(b)) == 1 }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/serverless_test.go
rest/serverless_test.go
package rest import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/core/logx/logtest" ) func TestNewServerless(t *testing.T) { logtest.Discard(t) const configYaml = ` Name: foo Host: localhost Port: 0 ` var cnf RestConf assert.Nil(t, conf.LoadFromYamlBytes([]byte(configYaml), &cnf)) svr, err := NewServer(cnf) assert.NoError(t, err) svr.AddRoute(Route{ Method: http.MethodGet, Path: "/", Handler: func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello World")) }, }) serverless, err := NewServerless(svr) assert.NoError(t, err) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/", nil) serverless.Serve(w, r) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "Hello World", w.Body.String()) } func TestNewServerlessWithError(t *testing.T) { logtest.Discard(t) const configYaml = ` Name: foo Host: localhost Port: 0 ` var cnf RestConf assert.Nil(t, conf.LoadFromYamlBytes([]byte(configYaml), &cnf)) svr, err := NewServer(cnf) assert.NoError(t, err) svr.AddRoute(Route{ Method: http.MethodGet, Path: "notstartwith/", Handler: nil, }) _, err = NewServerless(svr) assert.Error(t, err) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/serverless.go
rest/serverless.go
package rest import "net/http" // Serverless is a wrapper around Server that allows it to be used in serverless environments. type Serverless struct { server *Server } // NewServerless creates a new Serverless instance from the provided Server. func NewServerless(server *Server) (*Serverless, error) { // Ensure the server is built before using it in a serverless context. // Why not call server.build() when serving requests, // is because we need to ensure fail fast behavior. if err := server.build(); err != nil { return nil, err } return &Serverless{ server: server, }, nil } // Serve handles HTTP requests by delegating them to the underlying Server instance. func (s *Serverless) Serve(w http.ResponseWriter, r *http.Request) { s.server.serve(w, r) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/types.go
rest/types.go
package rest import ( "net/http" "time" ) type ( // Middleware defines the middleware method. Middleware func(next http.HandlerFunc) http.HandlerFunc // A Route is a http route. Route struct { Method string Path string Handler http.HandlerFunc } // RouteOption defines the method to customize a featured route. RouteOption func(r *featuredRoutes) jwtSetting struct { enabled bool secret string prevSecret string } signatureSetting struct { SignatureConf enabled bool } featuredRoutes struct { timeout *time.Duration priority bool jwt jwtSetting signature signatureSetting sse bool routes []Route maxBytes int64 } )
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/server_test.go
rest/server_test.go
package rest import ( "crypto/tls" "embed" "fmt" "io" "io/fs" "net/http" "net/http/httptest" "os" "strings" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/core/logx/logtest" "github.com/zeromicro/go-zero/rest/chain" "github.com/zeromicro/go-zero/rest/httpx" "github.com/zeromicro/go-zero/rest/internal/cors" "github.com/zeromicro/go-zero/rest/internal/header" "github.com/zeromicro/go-zero/rest/router" ) const ( exampleContent = "example content" sampleContent = "sample content" ) func TestNewServer(t *testing.T) { logtest.Discard(t) const configYaml = ` Name: foo Host: localhost Port: 0 ` var cnf RestConf assert.Nil(t, conf.LoadFromYamlBytes([]byte(configYaml), &cnf)) tests := []struct { c RestConf opts []RunOption fail bool }{ { c: RestConf{}, opts: []RunOption{WithRouter(mockedRouter{}), WithCors()}, }, { c: cnf, opts: []RunOption{WithRouter(mockedRouter{})}, }, { c: cnf, opts: []RunOption{WithRouter(mockedRouter{}), WithNotAllowedHandler(nil)}, }, { c: cnf, opts: []RunOption{WithNotFoundHandler(nil), WithRouter(mockedRouter{})}, }, { c: cnf, opts: []RunOption{WithUnauthorizedCallback(nil), WithRouter(mockedRouter{})}, }, { c: cnf, opts: []RunOption{WithUnsignedCallback(nil), WithRouter(mockedRouter{})}, }, } for _, test := range tests { var svr *Server var err error if test.fail { _, err = NewServer(test.c, test.opts...) assert.NotNil(t, err) continue } else { svr = MustNewServer(test.c, test.opts...) } svr.Use(ToMiddleware(func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { next.ServeHTTP(w, r) }) })) svr.AddRoute(Route{ Method: http.MethodGet, Path: "/", Handler: nil, }, WithJwt("thesecret"), WithSignature(SignatureConf{}), WithJwtTransition("previous", "thenewone")) func() { defer func() { p := recover() switch v := p.(type) { case error: assert.Equal(t, "foo", v.Error()) default: t.Fail() } }() svr.Start() svr.Stop() }() func() { defer func() { p := recover() switch v := p.(type) { case error: assert.Equal(t, "foo", v.Error()) default: t.Fail() } }() svr.StartWithOpts(func(svr *http.Server) { svr.RegisterOnShutdown(func() {}) }) svr.Stop() }() } } func TestWithMaxBytes(t *testing.T) { const maxBytes = 1000 var fr featuredRoutes WithMaxBytes(maxBytes)(&fr) assert.Equal(t, int64(maxBytes), fr.maxBytes) } func TestWithMiddleware(t *testing.T) { m := make(map[string]string) rt := router.NewRouter() handler := func(w http.ResponseWriter, r *http.Request) { var v struct { Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode"` } err := httpx.Parse(r, &v) assert.Nil(t, err) _, err = io.WriteString(w, fmt.Sprintf("%s:%d", v.Nickname, v.Zipcode)) assert.Nil(t, err) } rs := WithMiddleware(func(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var v struct { Name string `path:"name"` Year string `path:"year"` } assert.Nil(t, httpx.ParsePath(r, &v)) m[v.Name] = v.Year next.ServeHTTP(w, r) } }, Route{ Method: http.MethodGet, Path: "/first/:name/:year", Handler: handler, }, Route{ Method: http.MethodGet, Path: "/second/:name/:year", Handler: handler, }) urls := []string{ "http://hello.com/first/kevin/2017?nickname=whatever&zipcode=200000", "http://hello.com/second/wan/2020?nickname=whatever&zipcode=200000", } for _, route := range rs { assert.Nil(t, rt.Handle(route.Method, route.Path, route.Handler)) } for _, url := range urls { r, err := http.NewRequest(http.MethodGet, url, nil) assert.Nil(t, err) rr := httptest.NewRecorder() rt.ServeHTTP(rr, r) assert.Equal(t, "whatever:200000", rr.Body.String()) } assert.EqualValues(t, map[string]string{ "kevin": "2017", "wan": "2020", }, m) } func TestWithFileServerMiddleware(t *testing.T) { tests := []struct { name string path string dir string requestPath string expectedStatus int expectedContent string }{ { name: "Serve static file", path: "/assets/", dir: "./testdata", requestPath: "/assets/example.txt", expectedStatus: http.StatusOK, expectedContent: exampleContent, }, { name: "Pass through non-matching path", path: "/static/", dir: "./testdata", requestPath: "/other/path", expectedStatus: http.StatusNotFound, }, { name: "Directory with trailing slash", path: "/static", dir: "testdata", requestPath: "/static/sample.txt", expectedStatus: http.StatusOK, expectedContent: sampleContent, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { server := MustNewServer(RestConf{}, WithFileServer(tt.path, http.Dir(tt.dir))) req := httptest.NewRequest(http.MethodGet, tt.requestPath, nil) rr := httptest.NewRecorder() serve(server, rr, req) assert.Equal(t, tt.expectedStatus, rr.Code) if len(tt.expectedContent) > 0 { assert.Equal(t, tt.expectedContent, rr.Body.String()) } }) } } func TestMultiMiddlewares(t *testing.T) { m := make(map[string]string) rt := router.NewRouter() handler := func(w http.ResponseWriter, r *http.Request) { var v struct { Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode"` } err := httpx.Parse(r, &v) assert.Nil(t, err) _, err = io.WriteString(w, fmt.Sprintf("%s:%s", v.Nickname, m[v.Nickname])) assert.Nil(t, err) } rs := WithMiddlewares([]Middleware{ func(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var v struct { Name string `path:"name"` Year string `path:"year"` } assert.Nil(t, httpx.ParsePath(r, &v)) m[v.Name] = v.Year next.ServeHTTP(w, r) } }, func(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var v struct { Name string `form:"nickname"` Zipcode string `form:"zipcode"` } assert.Nil(t, httpx.ParseForm(r, &v)) assert.NotEmpty(t, m) m[v.Name] = v.Zipcode + v.Zipcode next.ServeHTTP(w, r) } }, ToMiddleware(func(next http.Handler) http.Handler { return next }), }, Route{ Method: http.MethodGet, Path: "/first/:name/:year", Handler: handler, }, Route{ Method: http.MethodGet, Path: "/second/:name/:year", Handler: handler, }) urls := []string{ "http://hello.com/first/kevin/2017?nickname=whatever&zipcode=200000", "http://hello.com/second/wan/2020?nickname=whatever&zipcode=200000", } for _, route := range rs { assert.Nil(t, rt.Handle(route.Method, route.Path, route.Handler)) } for _, url := range urls { r, err := http.NewRequest(http.MethodGet, url, nil) assert.Nil(t, err) rr := httptest.NewRecorder() rt.ServeHTTP(rr, r) assert.Equal(t, "whatever:200000200000", rr.Body.String()) } assert.EqualValues(t, map[string]string{ "kevin": "2017", "wan": "2020", "whatever": "200000200000", }, m) } func TestWithPrefix(t *testing.T) { fr := featuredRoutes{ routes: []Route{ { Path: "/hello", }, { Path: "/world", }, }, } WithPrefix("/api")(&fr) vals := make([]string, 0, len(fr.routes)) for _, r := range fr.routes { vals = append(vals, r.Path) } assert.EqualValues(t, []string{"/api/hello", "/api/world"}, vals) } func TestWithPriority(t *testing.T) { var fr featuredRoutes WithPriority()(&fr) assert.True(t, fr.priority) } func TestWithTimeout(t *testing.T) { var fr featuredRoutes WithTimeout(time.Hour)(&fr) assert.Equal(t, time.Hour, *fr.timeout) } func TestWithTLSConfig(t *testing.T) { const configYaml = ` Name: foo Port: 54321 ` var cnf RestConf assert.Nil(t, conf.LoadFromYamlBytes([]byte(configYaml), &cnf)) testConfig := &tls.Config{ CipherSuites: []uint16{ tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, }, } testCases := []struct { c RestConf opts []RunOption res *tls.Config }{ { c: cnf, opts: []RunOption{WithTLSConfig(testConfig)}, res: testConfig, }, { c: cnf, opts: []RunOption{WithUnsignedCallback(nil)}, res: nil, }, } for _, testCase := range testCases { svr, err := NewServer(testCase.c, testCase.opts...) assert.Nil(t, err) assert.Equal(t, svr.ngin.tlsConfig, testCase.res) } } func TestWithCors(t *testing.T) { const configYaml = ` Name: foo Port: 54321 ` var cnf RestConf assert.Nil(t, conf.LoadFromYamlBytes([]byte(configYaml), &cnf)) rt := router.NewRouter() svr, err := NewServer(cnf, WithRouter(rt)) assert.Nil(t, err) defer svr.Stop() opt := WithCors("local") opt(svr) } func TestWithCustomCors(t *testing.T) { const configYaml = ` Name: foo Port: 54321 ` var cnf RestConf assert.Nil(t, conf.LoadFromYamlBytes([]byte(configYaml), &cnf)) rt := router.NewRouter() svr, err := NewServer(cnf, WithRouter(rt)) assert.Nil(t, err) opt := WithCustomCors(func(header http.Header) { header.Set("foo", "bar") }, func(w http.ResponseWriter) { w.WriteHeader(http.StatusOK) }, "local") opt(svr) } func TestWithCorsHeaders(t *testing.T) { tests := []struct { name string headers []string }{ { name: "single header", headers: []string{"UserHeader"}, }, { name: "multiple headers", headers: []string{"UserHeader", "X-Requested-With"}, }, { name: "no headers", headers: []string{}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { const configYaml = ` Name: foo Port: 54321 ` var cnf RestConf assert.Nil(t, conf.LoadFromYamlBytes([]byte(configYaml), &cnf)) rt := router.NewRouter() svr, err := NewServer(cnf, WithRouter(rt)) assert.Nil(t, err) defer svr.Stop() option := WithCorsHeaders(tt.headers...) option(svr) // Assuming newCorsRouter sets headers correctly, // we would need to verify the behavior here. Since we don't have // direct access to headers, we'll mock newCorsRouter to capture it. w := httptest.NewRecorder() serve(svr, w, httptest.NewRequest(http.MethodOptions, "/", nil)) vals := w.Header().Values("Access-Control-Allow-Headers") respHeaders := make(map[string]struct{}) for _, header := range vals { headers := strings.Split(header, ", ") for _, h := range headers { if len(h) > 0 { respHeaders[h] = struct{}{} } } } for _, h := range tt.headers { _, ok := respHeaders[h] assert.Truef(t, ok, "expected header %s not found", h) } }) } } func TestServer_PrintRoutes(t *testing.T) { const ( configYaml = ` Name: foo Port: 54321 ` expect = `Routes: GET /bar GET /foo GET /foo/:bar GET /foo/:bar/baz ` ) var cnf RestConf assert.Nil(t, conf.LoadFromYamlBytes([]byte(configYaml), &cnf)) svr, err := NewServer(cnf) assert.Nil(t, err) svr.AddRoutes([]Route{ { Method: http.MethodGet, Path: "/foo", Handler: http.NotFound, }, { Method: http.MethodGet, Path: "/bar", Handler: http.NotFound, }, { Method: http.MethodGet, Path: "/foo/:bar", Handler: http.NotFound, }, { Method: http.MethodGet, Path: "/foo/:bar/baz", Handler: http.NotFound, }, }) old := os.Stdout r, w, err := os.Pipe() assert.Nil(t, err) os.Stdout = w defer func() { os.Stdout = old }() svr.PrintRoutes() ch := make(chan string) go func() { var buf strings.Builder io.Copy(&buf, r) ch <- buf.String() }() w.Close() out := <-ch assert.Equal(t, expect, out) } func TestServer_Routes(t *testing.T) { const ( configYaml = ` Name: foo Port: 54321 ` expect = `GET /foo GET /bar GET /foo/:bar GET /foo/:bar/baz` ) var cnf RestConf assert.Nil(t, conf.LoadFromYamlBytes([]byte(configYaml), &cnf)) svr, err := NewServer(cnf) assert.Nil(t, err) svr.AddRoutes([]Route{ { Method: http.MethodGet, Path: "/foo", Handler: http.NotFound, }, { Method: http.MethodGet, Path: "/bar", Handler: http.NotFound, }, { Method: http.MethodGet, Path: "/foo/:bar", Handler: http.NotFound, }, { Method: http.MethodGet, Path: "/foo/:bar/baz", Handler: http.NotFound, }, }) routes := svr.Routes() var buf strings.Builder for i := 0; i < len(routes); i++ { buf.WriteString(routes[i].Method) buf.WriteString(" ") buf.WriteString(routes[i].Path) buf.WriteString(" ") } assert.Equal(t, expect, strings.Trim(buf.String(), " ")) } func TestHandleError(t *testing.T) { assert.NotPanics(t, func() { handleError(nil) handleError(http.ErrServerClosed) }) } func TestValidateSecret(t *testing.T) { assert.Panics(t, func() { validateSecret("short") }) } func TestServer_WithChain(t *testing.T) { var called int32 middleware1 := func() func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { atomic.AddInt32(&called, 1) next.ServeHTTP(w, r) atomic.AddInt32(&called, 1) }) } } middleware2 := func() func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { atomic.AddInt32(&called, 1) next.ServeHTTP(w, r) atomic.AddInt32(&called, 1) }) } } server := MustNewServer(RestConf{}, WithChain(chain.New(middleware1(), middleware2()))) server.AddRoutes( []Route{ { Method: http.MethodGet, Path: "/", Handler: func(_ http.ResponseWriter, _ *http.Request) { atomic.AddInt32(&called, 1) }, }, }, ) rt := router.NewRouter() assert.Nil(t, server.ngin.bindRoutes(rt)) req, err := http.NewRequest(http.MethodGet, "/", http.NoBody) assert.Nil(t, err) rt.ServeHTTP(httptest.NewRecorder(), req) assert.Equal(t, int32(5), atomic.LoadInt32(&called)) } func TestServer_WithCors(t *testing.T) { var called int32 middleware := func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { atomic.AddInt32(&called, 1) next.ServeHTTP(w, r) }) } r := router.NewRouter() assert.Nil(t, r.Handle(http.MethodOptions, "/", middleware(http.NotFoundHandler()))) cr := &corsRouter{ Router: r, middleware: cors.Middleware(nil, "*"), } req := httptest.NewRequest(http.MethodOptions, "/", http.NoBody) cr.ServeHTTP(httptest.NewRecorder(), req) assert.Equal(t, int32(0), atomic.LoadInt32(&called)) } func TestServer_ServeHTTP(t *testing.T) { const configYaml = ` Name: foo Port: 54321 ` var cnf RestConf assert.Nil(t, conf.LoadFromYamlBytes([]byte(configYaml), &cnf)) svr, err := NewServer(cnf) assert.Nil(t, err) svr.AddRoutes([]Route{ { Method: http.MethodGet, Path: "/foo", Handler: func(writer http.ResponseWriter, request *http.Request) { _, _ = writer.Write([]byte("succeed")) writer.WriteHeader(http.StatusOK) }, }, { Method: http.MethodGet, Path: "/bar", Handler: func(writer http.ResponseWriter, request *http.Request) { _, _ = writer.Write([]byte("succeed")) writer.WriteHeader(http.StatusOK) }, }, { Method: http.MethodGet, Path: "/user/:name", Handler: func(writer http.ResponseWriter, request *http.Request) { var userInfo struct { Name string `path:"name"` } err := httpx.Parse(request, &userInfo) if err != nil { _, _ = writer.Write([]byte("failed")) writer.WriteHeader(http.StatusBadRequest) return } _, _ = writer.Write([]byte("succeed")) writer.WriteHeader(http.StatusOK) }, }, }) testCase := []struct { name string path string code int }{ { name: "URI : /foo", path: "/foo", code: http.StatusOK, }, { name: "URI : /bar", path: "/bar", code: http.StatusOK, }, { name: "URI : undefined path", path: "/test", code: http.StatusNotFound, }, { name: "URI : /user/:name", path: "/user/abc", code: http.StatusOK, }, } for _, test := range testCase { t.Run(test.name, func(t *testing.T) { w := httptest.NewRecorder() req, _ := http.NewRequest("GET", test.path, nil) serve(svr, w, req) assert.Equal(t, test.code, w.Code) }) } } func TestServerEventStream(t *testing.T) { server := MustNewServer(RestConf{}) server.AddRoutes([]Route{ { Method: http.MethodGet, Path: "/foo", Handler: func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("foo")) }, }, { Method: http.MethodGet, Path: "/bar", Handler: func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("bar")) }, }, }, WithSSE()) check := func(val string) { req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("/%s", val), http.NoBody) assert.Nil(t, err) rr := httptest.NewRecorder() serve(server, rr, req) assert.Equal(t, http.StatusOK, rr.Code) assert.Equal(t, header.ContentTypeEventStream, rr.Header().Get(header.ContentType)) assert.Equal(t, header.CacheControlNoCache, rr.Header().Get(header.CacheControl)) assert.Equal(t, header.ConnectionKeepAlive, rr.Header().Get(header.Connection)) assert.Equal(t, val, rr.Body.String()) } check("foo") check("bar") } //go:embed testdata var content embed.FS func TestServerEmbedFileSystem(t *testing.T) { filesys, err := fs.Sub(content, "testdata") assert.NoError(t, err) server := MustNewServer(RestConf{}, WithFileServer("/assets", http.FS(filesys))) req, err := http.NewRequest(http.MethodGet, "/assets/sample.txt", http.NoBody) assert.Nil(t, err) rr := httptest.NewRecorder() serve(server, rr, req) assert.Equal(t, sampleContent, rr.Body.String()) } // serve is for test purpose, allow developer to do a unit test with // all defined routes without starting an HTTP Server. // // For example: // // server := MustNewServer(...) // server.addRoute(...) // router a // server.addRoute(...) // router b // server.addRoute(...) // router c // // r, _ := http.NewRequest(...) // w := httptest.NewRecorder(...) // serve(server, w, r) // // verify the response func serve(s *Server, w http.ResponseWriter, r *http.Request) { _ = s.build() s.serve(w, r) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/config.go
rest/config.go
package rest import ( "time" "github.com/zeromicro/go-zero/core/service" ) type ( // MiddlewaresConf is the config of middlewares. MiddlewaresConf struct { Trace bool `json:",default=true"` Log bool `json:",default=true"` Prometheus bool `json:",default=true"` MaxConns bool `json:",default=true"` Breaker bool `json:",default=true"` Shedding bool `json:",default=true"` Timeout bool `json:",default=true"` Recover bool `json:",default=true"` Metrics bool `json:",default=true"` MaxBytes bool `json:",default=true"` Gunzip bool `json:",default=true"` } // A PrivateKeyConf is a private key config. PrivateKeyConf struct { Fingerprint string KeyFile string } // A SignatureConf is a signature config. SignatureConf struct { Strict bool `json:",default=false"` Expiry time.Duration `json:",default=1h"` PrivateKeys []PrivateKeyConf } // A RestConf is a http service config. // Why not name it as Conf, because we need to consider usage like: // type Config struct { // zrpc.RpcConf // rest.RestConf // } // if with the name Conf, there will be two Conf inside Config. RestConf struct { service.ServiceConf Host string `json:",default=0.0.0.0"` Port int CertFile string `json:",optional"` KeyFile string `json:",optional"` Verbose bool `json:",optional"` MaxConns int `json:",default=10000"` MaxBytes int64 `json:",default=1048576"` // milliseconds Timeout int64 `json:",default=3000"` CpuThreshold int64 `json:",default=900,range=[0:1000)"` Signature SignatureConf `json:",optional"` // There are default values for all the items in Middlewares. Middlewares MiddlewaresConf // TraceIgnorePaths is paths blacklist for trace middleware. TraceIgnorePaths []string `json:",optional"` } )
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/engine_test.go
rest/engine_test.go
package rest import ( "context" "crypto/tls" "errors" "fmt" "net/http" "net/http/httptest" "os" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/core/fs" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/rest/router" ) const ( priKey = `-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQC4TJk3onpqb2RYE3wwt23J9SHLFstHGSkUYFLe+nl1dEKHbD+/ Zt95L757J3xGTrwoTc7KCTxbrgn+stn0w52BNjj/kIE2ko4lbh/v8Fl14AyVR9ms fKtKOnhe5FCT72mdtApr+qvzcC3q9hfXwkyQU32pv7q5UimZ205iKSBmgQIDAQAB AoGAM5mWqGIAXj5z3MkP01/4CDxuyrrGDVD5FHBno3CDgyQa4Gmpa4B0/ywj671B aTnwKmSmiiCN2qleuQYASixes2zY5fgTzt+7KNkl9JHsy7i606eH2eCKzsUa/s6u WD8V3w/hGCQ9zYI18ihwyXlGHIgcRz/eeRh+nWcWVJzGOPUCQQD5nr6It/1yHb1p C6l4fC4xXF19l4KxJjGu1xv/sOpSx0pOqBDEX3Mh//FU954392rUWDXV1/I65BPt TLphdsu3AkEAvQJ2Qay/lffFj9FaUrvXuftJZ/Ypn0FpaSiUh3Ak3obBT6UvSZS0 bcYdCJCNHDtBOsWHnIN1x+BcWAPrdU7PhwJBAIQ0dUlH2S3VXnoCOTGc44I1Hzbj Rc65IdsuBqA3fQN2lX5vOOIog3vgaFrOArg1jBkG1wx5IMvb/EnUN2pjVqUCQCza KLXtCInOAlPemlCHwumfeAvznmzsWNdbieOZ+SXVVIpR6KbNYwOpv7oIk3Pfm9sW hNffWlPUKhW42Gc+DIECQQDmk20YgBXwXWRM5DRPbhisIV088N5Z58K9DtFWkZsd OBDT3dFcgZONtlmR1MqZO0pTh30lA4qovYj3Bx7A8i36 -----END RSA PRIVATE KEY-----` ) func TestNewEngine(t *testing.T) { priKeyfile, err := fs.TempFilenameWithText(priKey) assert.Nil(t, err) defer os.Remove(priKeyfile) yamls := []string{ `Name: foo Host: localhost Port: 0 Middlewares: Log: false `, `Name: foo Host: localhost Port: 0 CpuThreshold: 500 Middlewares: Log: false `, `Name: foo Host: localhost Port: 0 CpuThreshold: 500 Verbose: true `, } routes := []featuredRoutes{ { jwt: jwtSetting{}, signature: signatureSetting{}, routes: []Route{{ Method: http.MethodGet, Path: "/", Handler: func(w http.ResponseWriter, r *http.Request) {}, }}, timeout: ptrOfDuration(time.Minute), }, { jwt: jwtSetting{}, signature: signatureSetting{}, routes: []Route{{ Method: http.MethodGet, Path: "/", Handler: func(w http.ResponseWriter, r *http.Request) {}, }}, timeout: ptrOfDuration(0), }, { priority: true, jwt: jwtSetting{}, signature: signatureSetting{}, routes: []Route{{ Method: http.MethodGet, Path: "/", Handler: func(w http.ResponseWriter, r *http.Request) {}, }}, timeout: ptrOfDuration(time.Second), }, { priority: true, jwt: jwtSetting{ enabled: true, }, signature: signatureSetting{}, routes: []Route{{ Method: http.MethodGet, Path: "/", Handler: func(w http.ResponseWriter, r *http.Request) {}, }}, }, { priority: true, jwt: jwtSetting{ enabled: true, prevSecret: "thesecret", }, signature: signatureSetting{}, routes: []Route{{ Method: http.MethodGet, Path: "/", Handler: func(w http.ResponseWriter, r *http.Request) {}, }}, }, { priority: true, jwt: jwtSetting{ enabled: true, }, signature: signatureSetting{}, routes: []Route{{ Method: http.MethodGet, Path: "/", Handler: func(w http.ResponseWriter, r *http.Request) {}, }}, }, { priority: true, jwt: jwtSetting{ enabled: true, }, signature: signatureSetting{ enabled: true, }, routes: []Route{{ Method: http.MethodGet, Path: "/", Handler: func(w http.ResponseWriter, r *http.Request) {}, }}, }, { priority: true, jwt: jwtSetting{ enabled: true, }, signature: signatureSetting{ enabled: true, SignatureConf: SignatureConf{ Strict: true, }, }, routes: []Route{{ Method: http.MethodGet, Path: "/", Handler: func(w http.ResponseWriter, r *http.Request) {}, }}, }, { priority: true, jwt: jwtSetting{ enabled: true, }, signature: signatureSetting{ enabled: true, SignatureConf: SignatureConf{ Strict: true, PrivateKeys: []PrivateKeyConf{ { Fingerprint: "a", KeyFile: "b", }, }, }, }, routes: []Route{{ Method: http.MethodGet, Path: "/", Handler: func(w http.ResponseWriter, r *http.Request) {}, }}, }, { priority: true, jwt: jwtSetting{ enabled: true, }, signature: signatureSetting{ enabled: true, SignatureConf: SignatureConf{ Strict: true, PrivateKeys: []PrivateKeyConf{ { Fingerprint: "a", KeyFile: priKeyfile, }, }, }, }, routes: []Route{{ Method: http.MethodGet, Path: "/", Handler: func(w http.ResponseWriter, r *http.Request) {}, }}, }, } var index int32 for _, yaml := range yamls { yaml := yaml for _, route := range routes { route := route t.Run(fmt.Sprintf("%s-%v", yaml, route.routes), func(t *testing.T) { var cnf RestConf assert.Nil(t, conf.LoadFromYamlBytes([]byte(yaml), &cnf)) ng := newEngine(cnf) if atomic.AddInt32(&index, 1)%2 == 0 { ng.setUnsignedCallback(func(w http.ResponseWriter, r *http.Request, next http.Handler, strict bool, code int) { }) } ng.addRoutes(route) ng.use(func(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { next.ServeHTTP(w, r) } }) assert.NotNil(t, ng.start(mockedRouter{}, func(svr *http.Server) { })) timeout := time.Second * 3 if route.timeout != nil { if *route.timeout == 0 { timeout = 0 } else if *route.timeout > timeout { timeout = *route.timeout } } assert.Equal(t, timeout, ng.timeout) }) } } } func TestNewEngine_unsignedCallback(t *testing.T) { priKeyfile, err := fs.TempFilenameWithText(priKey) assert.Nil(t, err) defer os.Remove(priKeyfile) yaml := `Name: foo Host: localhost Port: 0 Middlewares: Log: false ` route := featuredRoutes{ priority: true, jwt: jwtSetting{ enabled: true, }, signature: signatureSetting{ enabled: true, SignatureConf: SignatureConf{ Strict: true, PrivateKeys: []PrivateKeyConf{ { Fingerprint: "a", KeyFile: priKeyfile, }, }, }, }, routes: []Route{{ Method: http.MethodGet, Path: "/", Handler: func(w http.ResponseWriter, r *http.Request) {}, }}, } var index int32 t.Run(fmt.Sprintf("%s-%v", yaml, route.routes), func(t *testing.T) { var cnf RestConf assert.Nil(t, conf.LoadFromYamlBytes([]byte(yaml), &cnf)) ng := newEngine(cnf) if atomic.AddInt32(&index, 1)%2 == 0 { ng.setUnsignedCallback(func(w http.ResponseWriter, r *http.Request, next http.Handler, strict bool, code int) { }) } ng.addRoutes(route) ng.use(func(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { next.ServeHTTP(w, r) } }) assert.NotNil(t, ng.start(mockedRouter{}, func(svr *http.Server) { })) assert.Equal(t, time.Duration(time.Second*3), ng.timeout) }) } func TestEngine_checkedTimeout(t *testing.T) { tests := []struct { name string timeout *time.Duration expect time.Duration }{ { name: "not set", expect: time.Second, }, { name: "less", timeout: ptrOfDuration(time.Millisecond * 500), expect: time.Millisecond * 500, }, { name: "equal", timeout: ptrOfDuration(time.Second), expect: time.Second, }, { name: "more", timeout: ptrOfDuration(time.Millisecond * 1500), expect: time.Millisecond * 1500, }, } ng := newEngine(RestConf{ Timeout: 1000, }) for _, test := range tests { assert.Equal(t, test.expect, ng.checkedTimeout(test.timeout)) } } func TestEngine_checkedMaxBytes(t *testing.T) { tests := []struct { name string maxBytes int64 expect int64 }{ { name: "not set", expect: 1000, }, { name: "less", maxBytes: 500, expect: 500, }, { name: "equal", maxBytes: 1000, expect: 1000, }, { name: "more", maxBytes: 1500, expect: 1500, }, } ng := newEngine(RestConf{ MaxBytes: 1000, }) for _, test := range tests { assert.Equal(t, test.expect, ng.checkedMaxBytes(test.maxBytes)) } } func TestEngine_notFoundHandler(t *testing.T) { logx.Disable() ng := newEngine(RestConf{}) ts := httptest.NewServer(ng.notFoundHandler(nil)) defer ts.Close() client := ts.Client() err := func(_ context.Context) error { req, err := http.NewRequest("GET", ts.URL+"/bad", http.NoBody) assert.Nil(t, err) res, err := client.Do(req) assert.Nil(t, err) assert.Equal(t, http.StatusNotFound, res.StatusCode) return res.Body.Close() }(context.Background()) assert.Nil(t, err) } func TestEngine_notFoundHandlerNotNil(t *testing.T) { logx.Disable() ng := newEngine(RestConf{}) var called int32 ts := httptest.NewServer(ng.notFoundHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { atomic.AddInt32(&called, 1) }))) defer ts.Close() client := ts.Client() err := func(_ context.Context) error { req, err := http.NewRequest("GET", ts.URL+"/bad", http.NoBody) assert.Nil(t, err) res, err := client.Do(req) assert.Nil(t, err) assert.Equal(t, http.StatusNotFound, res.StatusCode) return res.Body.Close() }(context.Background()) assert.Nil(t, err) assert.Equal(t, int32(1), atomic.LoadInt32(&called)) } func TestEngine_notFoundHandlerNotNilWriteHeader(t *testing.T) { logx.Disable() ng := newEngine(RestConf{}) var called int32 ts := httptest.NewServer(ng.notFoundHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { atomic.AddInt32(&called, 1) w.WriteHeader(http.StatusExpectationFailed) }))) defer ts.Close() client := ts.Client() err := func(_ context.Context) error { req, err := http.NewRequest("GET", ts.URL+"/bad", http.NoBody) assert.Nil(t, err) res, err := client.Do(req) assert.Nil(t, err) assert.Equal(t, http.StatusExpectationFailed, res.StatusCode) return res.Body.Close() }(context.Background()) assert.Nil(t, err) assert.Equal(t, int32(1), atomic.LoadInt32(&called)) } func TestEngine_withTimeout(t *testing.T) { logx.Disable() tests := []struct { name string timeout int64 }{ { name: "not set", }, { name: "set", timeout: 1000, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { ng := newEngine(RestConf{ Timeout: test.timeout, Middlewares: MiddlewaresConf{ Timeout: true, }, }) svr := &http.Server{} ng.withNetworkTimeout()(svr) assert.Equal(t, time.Duration(test.timeout)*time.Millisecond*4/5, svr.ReadTimeout) assert.Equal(t, time.Duration(0), svr.ReadHeaderTimeout) assert.Equal(t, time.Duration(test.timeout)*time.Millisecond*11/10, svr.WriteTimeout) assert.Equal(t, time.Duration(0), svr.IdleTimeout) }) } } func TestEngine_ReadWriteTimeout(t *testing.T) { logx.Disable() tests := []struct { name string timeout int64 middleware bool }{ { name: "0/false", timeout: 0, middleware: false, }, { name: "0/true", timeout: 0, middleware: true, }, { name: "set/false", timeout: 1000, middleware: false, }, { name: "both set", timeout: 1000, middleware: true, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { ng := newEngine(RestConf{ Timeout: test.timeout, Middlewares: MiddlewaresConf{ Timeout: test.middleware, }, }) svr := &http.Server{} ng.withNetworkTimeout()(svr) assert.Equal(t, time.Duration(0), svr.ReadHeaderTimeout) assert.Equal(t, time.Duration(0), svr.IdleTimeout) if test.timeout > 0 && test.middleware { assert.Equal(t, time.Duration(test.timeout)*time.Millisecond*4/5, svr.ReadTimeout) assert.Equal(t, time.Duration(test.timeout)*time.Millisecond*11/10, svr.WriteTimeout) } else { assert.Equal(t, time.Duration(0), svr.ReadTimeout) assert.Equal(t, time.Duration(0), svr.WriteTimeout) } }) } } func TestEngine_start(t *testing.T) { logx.Disable() t.Run("http", func(t *testing.T) { ng := newEngine(RestConf{ Host: "localhost", Port: -1, }) assert.Error(t, ng.start(router.NewRouter())) }) t.Run("https", func(t *testing.T) { ng := newEngine(RestConf{ Host: "localhost", Port: -1, CertFile: "foo", KeyFile: "bar", }) ng.tlsConfig = &tls.Config{} assert.Error(t, ng.start(router.NewRouter())) }) } type mockedRouter struct { } func (m mockedRouter) ServeHTTP(_ http.ResponseWriter, _ *http.Request) { } func (m mockedRouter) Handle(_, _ string, _ http.Handler) error { return errors.New("foo") } func (m mockedRouter) SetNotFoundHandler(_ http.Handler) { } func (m mockedRouter) SetNotAllowedHandler(_ http.Handler) { } func ptrOfDuration(d time.Duration) *time.Duration { return &d }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/server.go
rest/server.go
package rest import ( "crypto/tls" "errors" "net/http" "path" "time" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/rest/chain" "github.com/zeromicro/go-zero/rest/handler" "github.com/zeromicro/go-zero/rest/httpx" "github.com/zeromicro/go-zero/rest/internal" "github.com/zeromicro/go-zero/rest/internal/cors" "github.com/zeromicro/go-zero/rest/internal/fileserver" "github.com/zeromicro/go-zero/rest/router" ) type ( // RunOption defines the method to customize a Server. RunOption func(*Server) // StartOption defines the method to customize http server. StartOption = internal.StartOption // A Server is a http server. Server struct { ngin *engine router httpx.Router } ) // MustNewServer returns a server with given config of c and options defined in opts. // Be aware that later RunOption might overwrite previous one that write the same option. // The process will exit if error occurs. func MustNewServer(c RestConf, opts ...RunOption) *Server { server, err := NewServer(c, opts...) if err != nil { logx.Must(err) } return server } // NewServer returns a server with given config of c and options defined in opts. // Be aware that later RunOption might overwrite previous one that write the same option. func NewServer(c RestConf, opts ...RunOption) (*Server, error) { if err := c.SetUp(); err != nil { return nil, err } server := &Server{ ngin: newEngine(c), router: router.NewRouter(), } opts = append([]RunOption{WithNotFoundHandler(nil)}, opts...) for _, opt := range opts { opt(server) } return server, nil } // AddRoute adds given route into the Server. func (s *Server) AddRoute(r Route, opts ...RouteOption) { s.AddRoutes([]Route{r}, opts...) } // AddRoutes add given routes into the Server. func (s *Server) AddRoutes(rs []Route, opts ...RouteOption) { r := featuredRoutes{ routes: rs, } for _, opt := range opts { opt(&r) } s.ngin.addRoutes(r) } // PrintRoutes prints the added routes to stdout. func (s *Server) PrintRoutes() { s.ngin.print() } // Routes returns the HTTP routers that registered in the server. func (s *Server) Routes() []Route { routes := make([]Route, 0, len(s.ngin.routes)) for _, r := range s.ngin.routes { routes = append(routes, r.routes...) } return routes } // Start starts the Server. // Graceful shutdown is enabled by default. // Use proc.SetTimeToForceQuit to customize the graceful shutdown period. func (s *Server) Start() { handleError(s.ngin.start(s.router)) } // StartWithOpts starts the Server. // Graceful shutdown is enabled by default. // Use proc.SetTimeToForceQuit to customize the graceful shutdown period. func (s *Server) StartWithOpts(opts ...StartOption) { handleError(s.ngin.start(s.router, opts...)) } // Stop stops the Server. func (s *Server) Stop() { logx.Close() } // Use adds the given middleware in the Server. func (s *Server) Use(middleware Middleware) { s.ngin.use(middleware) } // build builds the Server and binds the routes to the router. func (s *Server) build() error { return s.ngin.bindRoutes(s.router) } // serve serves the HTTP requests using the Server's router. func (s *Server) serve(w http.ResponseWriter, r *http.Request) { s.router.ServeHTTP(w, r) } // ToMiddleware converts the given handler to a Middleware. func ToMiddleware(handler func(next http.Handler) http.Handler) Middleware { return func(handle http.HandlerFunc) http.HandlerFunc { return handler(handle).ServeHTTP } } // WithChain returns a RunOption that uses the given chain to replace the default chain. // JWT auth middleware and the middlewares that added by svr.Use() will be appended. func WithChain(chn chain.Chain) RunOption { return func(svr *Server) { svr.ngin.chain = chn } } // WithCors returns a func to enable CORS for given origin, or default to all origins (*). func WithCors(origin ...string) RunOption { return func(server *Server) { server.router.SetNotAllowedHandler(cors.NotAllowedHandler(nil, origin...)) server.router = newCorsRouter(server.router, nil, origin...) } } // WithCorsHeaders returns a RunOption to enable CORS with given headers. func WithCorsHeaders(headers ...string) RunOption { const allDomains = "*" return func(server *Server) { server.router.SetNotAllowedHandler(cors.NotAllowedHandler(nil, allDomains)) server.router = newCorsRouter(server.router, func(header http.Header) { cors.AddAllowHeaders(header, headers...) }, allDomains) } } // WithCustomCors returns a func to enable CORS for given origin, or default to all origins (*), // fn lets caller customizing the response. func WithCustomCors(middlewareFn func(header http.Header), notAllowedFn func(http.ResponseWriter), origin ...string) RunOption { return func(server *Server) { server.router.SetNotAllowedHandler(cors.NotAllowedHandler(notAllowedFn, origin...)) server.router = newCorsRouter(server.router, middlewareFn, origin...) } } // WithFileServer returns a RunOption to serve files from given dir with given path. func WithFileServer(path string, fs http.FileSystem) RunOption { return func(server *Server) { server.router = newFileServingRouter(server.router, path, fs) } } // WithJwt returns a func to enable jwt authentication in given route. func WithJwt(secret string) RouteOption { return func(r *featuredRoutes) { validateSecret(secret) r.jwt.enabled = true r.jwt.secret = secret } } // WithJwtTransition returns a func to enable jwt authentication as well as jwt secret transition. // Which means old and new jwt secrets work together for a period. func WithJwtTransition(secret, prevSecret string) RouteOption { return func(r *featuredRoutes) { // why not validate prevSecret, because prevSecret is an already used one, // even it not meet our requirement, we still need to allow the transition. validateSecret(secret) r.jwt.enabled = true r.jwt.secret = secret r.jwt.prevSecret = prevSecret } } // WithMaxBytes returns a RouteOption to set maxBytes with the given value. func WithMaxBytes(maxBytes int64) RouteOption { return func(r *featuredRoutes) { r.maxBytes = maxBytes } } // WithMiddlewares adds given middlewares to given routes. func WithMiddlewares(ms []Middleware, rs ...Route) []Route { for i := len(ms) - 1; i >= 0; i-- { rs = WithMiddleware(ms[i], rs...) } return rs } // WithMiddleware adds given middleware to given route. func WithMiddleware(middleware Middleware, rs ...Route) []Route { routes := make([]Route, len(rs)) for i := range rs { route := rs[i] routes[i] = Route{ Method: route.Method, Path: route.Path, Handler: middleware(route.Handler), } } return routes } // WithNotFoundHandler returns a RunOption with not found handler set to given handler. func WithNotFoundHandler(handler http.Handler) RunOption { return func(server *Server) { notFoundHandler := server.ngin.notFoundHandler(handler) server.router.SetNotFoundHandler(notFoundHandler) } } // WithNotAllowedHandler returns a RunOption with not allowed handler set to given handler. func WithNotAllowedHandler(handler http.Handler) RunOption { return func(server *Server) { server.router.SetNotAllowedHandler(handler) } } // WithPrefix adds group as a prefix to the route paths. func WithPrefix(group string) RouteOption { return func(r *featuredRoutes) { routes := make([]Route, 0, len(r.routes)) for _, rt := range r.routes { p := path.Join(group, rt.Path) routes = append(routes, Route{ Method: rt.Method, Path: p, Handler: rt.Handler, }) } r.routes = routes } } // WithPriority returns a RunOption with priority. func WithPriority() RouteOption { return func(r *featuredRoutes) { r.priority = true } } // WithRouter returns a RunOption that make server run with given router. func WithRouter(router httpx.Router) RunOption { return func(server *Server) { server.router = router } } // WithSignature returns a RouteOption to enable signature verification. func WithSignature(signature SignatureConf) RouteOption { return func(r *featuredRoutes) { r.signature.enabled = true r.signature.Strict = signature.Strict r.signature.Expiry = signature.Expiry r.signature.PrivateKeys = signature.PrivateKeys } } // WithSSE returns a RouteOption to enable server-sent events. func WithSSE() RouteOption { return func(r *featuredRoutes) { r.sse = true } } // WithTimeout returns a RouteOption to set timeout with given value. func WithTimeout(timeout time.Duration) RouteOption { return func(r *featuredRoutes) { r.timeout = &timeout } } // WithTLSConfig returns a RunOption that with given tls config. func WithTLSConfig(cfg *tls.Config) RunOption { return func(svr *Server) { svr.ngin.setTlsConfig(cfg) } } // WithUnauthorizedCallback returns a RunOption that with given unauthorized callback set. func WithUnauthorizedCallback(callback handler.UnauthorizedCallback) RunOption { return func(svr *Server) { svr.ngin.setUnauthorizedCallback(callback) } } // WithUnsignedCallback returns a RunOption that with given unsigned callback set. func WithUnsignedCallback(callback handler.UnsignedCallback) RunOption { return func(svr *Server) { svr.ngin.setUnsignedCallback(callback) } } func handleError(err error) { // ErrServerClosed means the server is closed manually if err == nil || errors.Is(err, http.ErrServerClosed) { return } logx.Error(err) panic(err) } func validateSecret(secret string) { if len(secret) < 8 { panic("secret's length can't be less than 8") } } type corsRouter struct { httpx.Router middleware Middleware } func newCorsRouter(router httpx.Router, headerFn func(http.Header), origins ...string) httpx.Router { return &corsRouter{ Router: router, middleware: cors.Middleware(headerFn, origins...), } } func (c *corsRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) { c.middleware(c.Router.ServeHTTP)(w, r) } type fileServingRouter struct { httpx.Router middleware Middleware } func newFileServingRouter(router httpx.Router, path string, fs http.FileSystem) httpx.Router { return &fileServingRouter{ Router: router, middleware: fileserver.Middleware(path, fs), } } func (f *fileServingRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) { f.middleware(f.Router.ServeHTTP)(w, r) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/engine.go
rest/engine.go
package rest import ( "crypto/tls" "errors" "fmt" "net/http" "sort" "time" "github.com/zeromicro/go-zero/core/codec" "github.com/zeromicro/go-zero/core/load" "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/core/stat" "github.com/zeromicro/go-zero/rest/chain" "github.com/zeromicro/go-zero/rest/handler" "github.com/zeromicro/go-zero/rest/httpx" "github.com/zeromicro/go-zero/rest/internal" "github.com/zeromicro/go-zero/rest/internal/header" "github.com/zeromicro/go-zero/rest/internal/response" ) // use 1000m to represent 100% const topCpuUsage = 1000 // ErrSignatureConfig is an error that indicates bad config for signature. var ErrSignatureConfig = errors.New("bad config for Signature") type engine struct { conf RestConf routes []featuredRoutes // timeout is the max timeout of all routes, // and is used to set http.Server.ReadTimeout and http.Server.WriteTimeout. // this network timeout is used to avoid DoS attacks by sending data slowly // or receiving data slowly with many connections to exhaust server resources. timeout time.Duration unauthorizedCallback handler.UnauthorizedCallback unsignedCallback handler.UnsignedCallback chain chain.Chain middlewares []Middleware shedder load.Shedder priorityShedder load.Shedder tlsConfig *tls.Config } func newEngine(c RestConf) *engine { svr := &engine{ conf: c, timeout: time.Duration(c.Timeout) * time.Millisecond, } if c.CpuThreshold > 0 { svr.shedder = load.NewAdaptiveShedder(load.WithCpuThreshold(c.CpuThreshold)) svr.priorityShedder = load.NewAdaptiveShedder(load.WithCpuThreshold( (c.CpuThreshold + topCpuUsage) >> 1)) } return svr } func (ng *engine) addRoutes(r featuredRoutes) { if r.sse { r.routes = buildSSERoutes(r.routes) } ng.routes = append(ng.routes, r) ng.mightUpdateTimeout(r) } func (ng *engine) appendAuthHandler(fr featuredRoutes, chn chain.Chain, verifier func(chain.Chain) chain.Chain) chain.Chain { if fr.jwt.enabled { if len(fr.jwt.prevSecret) == 0 { chn = chn.Append(handler.Authorize(fr.jwt.secret, handler.WithUnauthorizedCallback(ng.unauthorizedCallback))) } else { chn = chn.Append(handler.Authorize(fr.jwt.secret, handler.WithPrevSecret(fr.jwt.prevSecret), handler.WithUnauthorizedCallback(ng.unauthorizedCallback))) } } return verifier(chn) } func (ng *engine) bindFeaturedRoutes(router httpx.Router, fr featuredRoutes, metrics *stat.Metrics) error { verifier, err := ng.signatureVerifier(fr.signature) if err != nil { return err } for _, route := range fr.routes { if err := ng.bindRoute(fr, router, metrics, route, verifier); err != nil { return err } } return nil } func (ng *engine) bindRoute(fr featuredRoutes, router httpx.Router, metrics *stat.Metrics, route Route, verifier func(chain.Chain) chain.Chain) error { chn := ng.chain if chn == nil { chn = ng.buildChainWithNativeMiddlewares(fr, route, metrics) } chn = ng.appendAuthHandler(fr, chn, verifier) for _, middleware := range ng.middlewares { chn = chn.Append(convertMiddleware(middleware)) } handle := chn.ThenFunc(route.Handler) return router.Handle(route.Method, route.Path, handle) } func (ng *engine) bindRoutes(router httpx.Router) error { metrics := ng.createMetrics() for _, fr := range ng.routes { if err := ng.bindFeaturedRoutes(router, fr, metrics); err != nil { return err } } return nil } func (ng *engine) buildChainWithNativeMiddlewares(fr featuredRoutes, route Route, metrics *stat.Metrics) chain.Chain { chn := chain.New() if ng.conf.Middlewares.Trace { chn = chn.Append(handler.TraceHandler(ng.conf.Name, route.Path, handler.WithTraceIgnorePaths(ng.conf.TraceIgnorePaths))) } if ng.conf.Middlewares.Log { chn = chn.Append(ng.getLogHandler()) } if ng.conf.Middlewares.Prometheus { chn = chn.Append(handler.PrometheusHandler(route.Path, route.Method)) } if ng.conf.Middlewares.MaxConns { chn = chn.Append(handler.MaxConnsHandler(ng.conf.MaxConns)) } if ng.conf.Middlewares.Breaker { chn = chn.Append(handler.BreakerHandler(route.Method, route.Path, metrics)) } if ng.conf.Middlewares.Shedding { chn = chn.Append(handler.SheddingHandler(ng.getShedder(fr.priority), metrics)) } if ng.conf.Middlewares.Timeout { chn = chn.Append(handler.TimeoutHandler(ng.checkedTimeout(fr.timeout))) } if ng.conf.Middlewares.Recover { chn = chn.Append(handler.RecoverHandler) } if ng.conf.Middlewares.Metrics { chn = chn.Append(handler.MetricHandler(metrics)) } if ng.conf.Middlewares.MaxBytes { chn = chn.Append(handler.MaxBytesHandler(ng.checkedMaxBytes(fr.maxBytes))) } if ng.conf.Middlewares.Gunzip { chn = chn.Append(handler.GunzipHandler) } return chn } func (ng *engine) checkedMaxBytes(bytes int64) int64 { if bytes > 0 { return bytes } return ng.conf.MaxBytes } func (ng *engine) checkedTimeout(timeout *time.Duration) time.Duration { if timeout != nil { return *timeout } // if timeout not set in featured routes, use global timeout return time.Duration(ng.conf.Timeout) * time.Millisecond } func (ng *engine) createMetrics() *stat.Metrics { var metrics *stat.Metrics if len(ng.conf.Name) > 0 { metrics = stat.NewMetrics(ng.conf.Name) } else { metrics = stat.NewMetrics(fmt.Sprintf("%s:%d", ng.conf.Host, ng.conf.Port)) } return metrics } func (ng *engine) getLogHandler() func(http.Handler) http.Handler { if ng.conf.Verbose { return handler.DetailedLogHandler } return handler.LogHandler } func (ng *engine) getShedder(priority bool) load.Shedder { if priority && ng.priorityShedder != nil { return ng.priorityShedder } return ng.shedder } func (ng *engine) hasTimeout() bool { return ng.conf.Middlewares.Timeout && ng.timeout > 0 } // mightUpdateTimeout checks if the route timeout is greater than the current, // and updates the engine's timeout accordingly. func (ng *engine) mightUpdateTimeout(r featuredRoutes) { // if global timeout is set to 0, it means no need to set read/write timeout // if route timeout is nil, no need to update ng.timeout if ng.timeout == 0 || r.timeout == nil { return } // if route timeout is 0 (means no timeout), cannot set read/write timeout if *r.timeout == 0 { ng.timeout = 0 return } // need to guarantee the timeout is the max of all routes // otherwise impossible to set http.Server.ReadTimeout & WriteTimeout if *r.timeout > ng.timeout { ng.timeout = *r.timeout } } // notFoundHandler returns a middleware that handles 404 not found requests. func (ng *engine) notFoundHandler(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { chn := chain.New( handler.TraceHandler(ng.conf.Name, "", handler.WithTraceIgnorePaths(ng.conf.TraceIgnorePaths)), ) if ng.conf.Middlewares.Log { chn = chn.Append(ng.getLogHandler()) } var h http.Handler if next != nil { h = chn.Then(next) } else { h = chn.Then(http.NotFoundHandler()) } cw := response.NewHeaderOnceResponseWriter(w) h.ServeHTTP(cw, r) cw.WriteHeader(http.StatusNotFound) }) } func (ng *engine) print() { var routes []string for _, fr := range ng.routes { for _, route := range fr.routes { routes = append(routes, fmt.Sprintf("%s %s", route.Method, route.Path)) } } sort.Strings(routes) fmt.Println("Routes:") for _, route := range routes { fmt.Printf(" %s\n", route) } } func (ng *engine) setTlsConfig(cfg *tls.Config) { ng.tlsConfig = cfg } func (ng *engine) setUnauthorizedCallback(callback handler.UnauthorizedCallback) { ng.unauthorizedCallback = callback } func (ng *engine) setUnsignedCallback(callback handler.UnsignedCallback) { ng.unsignedCallback = callback } func (ng *engine) signatureVerifier(signature signatureSetting) (func(chain.Chain) chain.Chain, error) { if !signature.enabled { return func(chn chain.Chain) chain.Chain { return chn }, nil } if len(signature.PrivateKeys) == 0 { if signature.Strict { return nil, ErrSignatureConfig } return func(chn chain.Chain) chain.Chain { return chn }, nil } decrypters := make(map[string]codec.RsaDecrypter) for _, key := range signature.PrivateKeys { fingerprint := key.Fingerprint file := key.KeyFile decrypter, err := codec.NewRsaDecrypter(file) if err != nil { return nil, err } decrypters[fingerprint] = decrypter } return func(chn chain.Chain) chain.Chain { if ng.unsignedCallback == nil { return chn.Append(handler.LimitContentSecurityHandler(ng.conf.MaxBytes, decrypters, signature.Expiry, signature.Strict)) } return chn.Append(handler.LimitContentSecurityHandler(ng.conf.MaxBytes, decrypters, signature.Expiry, signature.Strict, ng.unsignedCallback)) }, nil } func (ng *engine) start(router httpx.Router, opts ...StartOption) error { if err := ng.bindRoutes(router); err != nil { return err } // make sure user defined options overwrite default options opts = append([]StartOption{ng.withNetworkTimeout()}, opts...) if len(ng.conf.CertFile) == 0 && len(ng.conf.KeyFile) == 0 { return internal.StartHttp(ng.conf.Host, ng.conf.Port, router, opts...) } // make sure user defined options overwrite default options opts = append([]StartOption{ func(svr *http.Server) { if ng.tlsConfig != nil { svr.TLSConfig = ng.tlsConfig } }, }, opts...) return internal.StartHttps(ng.conf.Host, ng.conf.Port, ng.conf.CertFile, ng.conf.KeyFile, router, opts...) } func (ng *engine) use(middleware Middleware) { ng.middlewares = append(ng.middlewares, middleware) } func (ng *engine) withNetworkTimeout() internal.StartOption { return func(svr *http.Server) { if !ng.hasTimeout() { return } // factor 0.8, to avoid clients send longer content-length than the actual content, // without this timeout setting, the server will time out and respond 503 Service Unavailable, // which triggers the circuit breaker. svr.ReadTimeout = 4 * ng.timeout / 5 // factor 1.1, to avoid servers don't have enough time to write responses. // setting the factor less than 1.0 may lead clients not receiving the responses. svr.WriteTimeout = 11 * ng.timeout / 10 } } func buildSSERoutes(routes []Route) []Route { for i, route := range routes { h := route.Handler routes[i].Handler = func(w http.ResponseWriter, r *http.Request) { // remove the default write deadline set by http.Server, // because SSE requires the connection to be kept alive indefinitely. rc := http.NewResponseController(w) if err := rc.SetWriteDeadline(time.Time{}); err != nil { // Some ResponseWriter implementations (like timeoutWriter) don't support SetWriteDeadline. // This is expected behavior and doesn't affect SSE functionality. logc.Debugf(r.Context(), "unable to clear write deadline for SSE connection: %v", err) } w.Header().Set(header.ContentType, header.ContentTypeEventStream) w.Header().Set(header.CacheControl, header.CacheControlNoCache) w.Header().Set(header.Connection, header.ConnectionKeepAlive) h(w, r) } } return routes } func convertMiddleware(ware Middleware) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return ware(next.ServeHTTP) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/chain/chain_test.go
rest/chain/chain_test.go
package chain import ( "net/http" "net/http/httptest" "reflect" "testing" "github.com/stretchr/testify/assert" ) // A constructor for middleware // that writes its own "tag" into the RW and does nothing else. // Useful in checking if a chain is behaving in the right order. func tagMiddleware(tag string) Middleware { return func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(tag)) h.ServeHTTP(w, r) }) } } // Not recommended (https://golang.org/pkg/reflect/#Value.Pointer), // but the best we can do. func funcsEqual(f1, f2 any) bool { val1 := reflect.ValueOf(f1) val2 := reflect.ValueOf(f2) return val1.Pointer() == val2.Pointer() } var testApp = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("app\n")) }) func TestNew(t *testing.T) { c1 := func(h http.Handler) http.Handler { return nil } c2 := func(h http.Handler) http.Handler { return http.StripPrefix("potato", nil) } slice := []Middleware{c1, c2} c := New(slice...) for k := range slice { assert.True(t, funcsEqual(c.(chain).middlewares[k], slice[k]), "New does not add constructors correctly") } } func TestThenWorksWithNoMiddleware(t *testing.T) { assert.True(t, funcsEqual(New().Then(testApp), testApp), "Then does not work with no middleware") } func TestThenTreatsNilAsDefaultServeMux(t *testing.T) { assert.Equal(t, http.DefaultServeMux, New().Then(nil), "Then does not treat nil as DefaultServeMux") } func TestThenFuncTreatsNilAsDefaultServeMux(t *testing.T) { assert.Equal(t, http.DefaultServeMux, New().ThenFunc(nil), "ThenFunc does not treat nil as DefaultServeMux") } func TestThenFuncConstructsHandlerFunc(t *testing.T) { fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) }) chained := New().ThenFunc(fn) rec := httptest.NewRecorder() chained.ServeHTTP(rec, (*http.Request)(nil)) assert.Equal(t, reflect.TypeOf((http.HandlerFunc)(nil)), reflect.TypeOf(chained), "ThenFunc does not construct HandlerFunc") } func TestThenOrdersHandlersCorrectly(t *testing.T) { t1 := tagMiddleware("t1\n") t2 := tagMiddleware("t2\n") t3 := tagMiddleware("t3\n") chained := New(t1, t2, t3).Then(testApp) w := httptest.NewRecorder() r, err := http.NewRequest("GET", "/", http.NoBody) if err != nil { t.Fatal(err) } chained.ServeHTTP(w, r) assert.Equal(t, "t1\nt2\nt3\napp\n", w.Body.String(), "Then does not order handlers correctly") } func TestAppendAddsHandlersCorrectly(t *testing.T) { c := New(tagMiddleware("t1\n"), tagMiddleware("t2\n")) c = c.Append(tagMiddleware("t3\n"), tagMiddleware("t4\n")) h := c.Then(testApp) w := httptest.NewRecorder() r, err := http.NewRequest("GET", "/", http.NoBody) assert.Nil(t, err) h.ServeHTTP(w, r) assert.Equal(t, "t1\nt2\nt3\nt4\napp\n", w.Body.String(), "Append does not add handlers correctly") } func TestExtendAddsHandlersCorrectly(t *testing.T) { c := New(tagMiddleware("t3\n"), tagMiddleware("t4\n")) c = c.Prepend(tagMiddleware("t1\n"), tagMiddleware("t2\n")) h := c.Then(testApp) w := httptest.NewRecorder() r, err := http.NewRequest("GET", "/", nil) assert.Nil(t, err) h.ServeHTTP(w, r) assert.Equal(t, "t1\nt2\nt3\nt4\napp\n", w.Body.String(), "Extend does not add handlers in correctly") }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/chain/chain.go
rest/chain/chain.go
package chain // This is a modified version of https://github.com/justinas/alice // The original code is licensed under the MIT license. // It's modified for couple reasons: // - Added the Chain interface // - Added support for the Chain.Prepend(...) method import "net/http" type ( // Chain defines a chain of middleware. Chain interface { Append(middlewares ...Middleware) Chain Prepend(middlewares ...Middleware) Chain Then(h http.Handler) http.Handler ThenFunc(fn http.HandlerFunc) http.Handler } // Middleware is an HTTP middleware. Middleware func(http.Handler) http.Handler // chain acts as a list of http.Handler middlewares. // chain is effectively immutable: // once created, it will always hold // the same set of middlewares in the same order. chain struct { middlewares []Middleware } ) // New creates a new Chain, memorizing the given list of middleware middlewares. // New serves no other function, middlewares are only called upon a call to Then() or ThenFunc(). func New(middlewares ...Middleware) Chain { return chain{middlewares: append(([]Middleware)(nil), middlewares...)} } // Append extends a chain, adding the specified middlewares as the last ones in the request flow. // // c := chain.New(m1, m2) // c.Append(m3, m4) // // requests in c go m1 -> m2 -> m3 -> m4 func (c chain) Append(middlewares ...Middleware) Chain { return chain{middlewares: join(c.middlewares, middlewares)} } // Prepend extends a chain by adding the specified chain as the first one in the request flow. // // c := chain.New(m3, m4) // c1 := chain.New(m1, m2) // c.Prepend(c1) // // requests in c go m1 -> m2 -> m3 -> m4 func (c chain) Prepend(middlewares ...Middleware) Chain { return chain{middlewares: join(middlewares, c.middlewares)} } // Then chains the middleware and returns the final http.Handler. // // New(m1, m2, m3).Then(h) // // is equivalent to: // // m1(m2(m3(h))) // // When the request comes in, it will be passed to m1, then m2, then m3 // and finally, the given handler // (assuming every middleware calls the following one). // // A chain can be safely reused by calling Then() several times. // // stdStack := chain.New(ratelimitHandler, csrfHandler) // indexPipe = stdStack.Then(indexHandler) // authPipe = stdStack.Then(authHandler) // // Note that middlewares are called on every call to Then() or ThenFunc() // and thus several instances of the same middleware will be created // when a chain is reused in this way. // For proper middleware, this should cause no problems. // // Then() treats nil as http.DefaultServeMux. func (c chain) Then(h http.Handler) http.Handler { if h == nil { h = http.DefaultServeMux } for i := range c.middlewares { h = c.middlewares[len(c.middlewares)-1-i](h) } return h } // ThenFunc works identically to Then, but takes // a HandlerFunc instead of a Handler. // // The following two statements are equivalent: // // c.Then(http.HandlerFunc(fn)) // c.ThenFunc(fn) // // ThenFunc provides all the guarantees of Then. func (c chain) ThenFunc(fn http.HandlerFunc) http.Handler { // This nil check cannot be removed due to the "nil is not nil" common mistake in Go. // Required due to: https://stackoverflow.com/questions/33426977/how-to-golang-check-a-variable-is-nil if fn == nil { return c.Then(nil) } return c.Then(fn) } func join(a, b []Middleware) []Middleware { mids := make([]Middleware, 0, len(a)+len(b)) mids = append(mids, a...) mids = append(mids, b...) return mids }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpc/service.go
rest/httpc/service.go
package httpc import ( "context" "errors" "net" "net/http" "net/url" "github.com/zeromicro/go-zero/core/breaker" ) type ( // Option is used to customize the *http.Client. Option func(r *http.Request) *http.Request // Service represents a remote HTTP service. Service interface { // Do sends an HTTP request with the given arguments and returns an HTTP response. Do(ctx context.Context, method, url string, data any) (*http.Response, error) // DoRequest sends a HTTP request to the service. DoRequest(r *http.Request) (*http.Response, error) } namedService struct { name string cli *http.Client opts []Option } ) // NewService returns a remote service with the given name. // opts are used to customize the *http.Client. func NewService(name string, opts ...Option) Service { return NewServiceWithClient(name, http.DefaultClient, opts...) } // NewServiceWithClient returns a remote service with the given name. // opts are used to customize the *http.Client. func NewServiceWithClient(name string, cli *http.Client, opts ...Option) Service { return namedService{ name: name, cli: cli, opts: opts, } } // Do sends an HTTP request with the given arguments and returns an HTTP response. func (s namedService) Do(ctx context.Context, method, url string, data any) (*http.Response, error) { req, err := buildRequest(ctx, method, url, data) if err != nil { return nil, err } return s.DoRequest(req) } // DoRequest sends an HTTP request to the service. func (s namedService) DoRequest(r *http.Request) (*http.Response, error) { return request(r, s) } func (s namedService) do(r *http.Request) (resp *http.Response, err error) { for _, opt := range s.opts { r = opt(r) } brk := breaker.GetBreaker(s.name) err = brk.DoWithAcceptableCtx(r.Context(), func() error { resp, err = s.cli.Do(r) return err }, func(err error) bool { return acceptable(resp, err) }) return } // acceptable determines whether the HTTP request/response should be considered // successful for circuit breaker purposes. // // Returns true (acceptable) for: // - HTTP status codes < 500 (2xx, 3xx, 4xx) // - Context cancellation (user-initiated) // - Non-network errors (application-level errors) // // Returns false (not acceptable, triggers breaker) for: // - HTTP status codes >= 500 (server errors) // - context.DeadlineExceeded (timeout) // - Network errors (connection refused, DNS failures, etc.) func acceptable(resp *http.Response, err error) bool { if err == nil { return resp.StatusCode < http.StatusInternalServerError } if errors.Is(err, context.DeadlineExceeded) { return false } if errors.Is(err, context.Canceled) { return true } // Unwrap url.Error if present var ue *url.Error if errors.As(err, &ue) { err = ue.Unwrap() } // Network errors are not acceptable var ne net.Error return !errors.As(err, &ne) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpc/service_test.go
rest/httpc/service_test.go
package httpc import ( "context" "errors" "net" "net/http" "net/http/httptest" "net/url" "testing" "time" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/rest/internal/header" ) func TestNamedService_DoRequest(t *testing.T) { svr := httptest.NewServer(http.RedirectHandler("/foo", http.StatusMovedPermanently)) defer svr.Close() req, err := http.NewRequest(http.MethodGet, svr.URL, nil) assert.Nil(t, err) service := NewService("foo") _, err = service.DoRequest(req) // too many redirects assert.NotNil(t, err) } func TestNamedService_DoRequestGet(t *testing.T) { svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("foo", r.Header.Get("foo")) })) defer svr.Close() service := NewService("foo", func(r *http.Request) *http.Request { r.Header.Set("foo", "bar") return r }) req, err := http.NewRequest(http.MethodGet, svr.URL, nil) assert.Nil(t, err) resp, err := service.DoRequest(req) assert.Nil(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, "bar", resp.Header.Get("foo")) } func TestNamedService_DoRequestPost(t *testing.T) { svr := httptest.NewServer(http.NotFoundHandler()) defer svr.Close() service := NewService("foo") req, err := http.NewRequest(http.MethodPost, svr.URL, nil) assert.Nil(t, err) req.Header.Set(header.ContentType, header.ContentTypeJson) resp, err := service.DoRequest(req) assert.Nil(t, err) assert.Equal(t, http.StatusNotFound, resp.StatusCode) } func TestNamedService_Do(t *testing.T) { type Data struct { Key string `path:"key"` Value int `form:"value"` Header string `header:"X-Header"` Body string `json:"body"` } svr := httptest.NewServer(http.NotFoundHandler()) defer svr.Close() service := NewService("foo") data := Data{ Key: "foo", Value: 10, Header: "my-header", Body: "my body", } resp, err := service.Do(context.Background(), http.MethodPost, svr.URL+"/nodes/:key", data) assert.Nil(t, err) assert.Equal(t, http.StatusNotFound, resp.StatusCode) } func TestNamedService_DoBadRequest(t *testing.T) { val := struct { Value string `json:"value,options=[a,b]"` }{ Value: "c", } service := NewService("foo") _, err := service.Do(context.Background(), http.MethodPost, "/nodes/:key", val) assert.NotNil(t, err) } // mockNetError implements net.Error interface for testing type mockNetError struct { msg string timeout bool temporary bool } func (e *mockNetError) Error() string { return e.msg } func (e *mockNetError) Timeout() bool { return e.timeout } func (e *mockNetError) Temporary() bool { return e.temporary } func TestAcceptable(t *testing.T) { tests := []struct { name string resp *http.Response err error expected bool }{ { name: "no error with 2xx status code", resp: &http.Response{ StatusCode: http.StatusOK, }, err: nil, expected: true, }, { name: "no error with 3xx status code", resp: &http.Response{ StatusCode: http.StatusMovedPermanently, }, err: nil, expected: true, }, { name: "no error with 4xx status code", resp: &http.Response{ StatusCode: http.StatusNotFound, }, err: nil, expected: true, }, { name: "no error with 499 status code (just below 500)", resp: &http.Response{ StatusCode: 499, }, err: nil, expected: true, }, { name: "no error with 500 status code", resp: &http.Response{ StatusCode: http.StatusInternalServerError, }, err: nil, expected: false, }, { name: "no error with 503 status code", resp: &http.Response{ StatusCode: http.StatusServiceUnavailable, }, err: nil, expected: false, }, { name: "context deadline exceeded", resp: nil, err: context.DeadlineExceeded, expected: false, }, { name: "context canceled", resp: nil, err: context.Canceled, expected: true, }, { name: "wrapped context deadline exceeded", resp: nil, err: errors.Join(context.DeadlineExceeded, errors.New("timeout")), expected: false, }, { name: "wrapped context canceled", resp: nil, err: errors.Join(context.Canceled, errors.New("canceled")), expected: true, }, { name: "network error - timeout", resp: nil, err: &mockNetError{msg: "network timeout", timeout: true, temporary: false}, expected: false, }, { name: "network error - temporary", resp: nil, err: &mockNetError{msg: "temporary network error", timeout: false, temporary: true}, expected: false, }, { name: "network error - connection refused", resp: nil, err: &net.OpError{Op: "dial", Net: "tcp", Err: errors.New("connection refused")}, expected: false, }, { name: "url.Error wrapping network error", resp: nil, err: &url.Error{ Op: "Get", URL: "http://example.com", Err: &mockNetError{msg: "network error", timeout: true}, }, expected: false, }, { name: "url.Error wrapping non-network error", resp: nil, err: &url.Error{ Op: "Get", URL: "http://example.com", Err: errors.New("some other error"), }, expected: true, }, { name: "url.Error wrapping context.DeadlineExceeded", resp: nil, err: &url.Error{ Op: "Get", URL: "http://example.com", Err: context.DeadlineExceeded, }, expected: false, }, { name: "url.Error wrapping context.Canceled", resp: nil, err: &url.Error{ Op: "Get", URL: "http://example.com", Err: context.Canceled, }, expected: true, }, { name: "generic error (non-network)", resp: nil, err: errors.New("some random error"), expected: true, }, { name: "EOF error (non-network)", resp: nil, err: errors.New("EOF"), expected: true, }, { name: "nil response with nil error (edge case)", resp: nil, err: nil, expected: false, // Will panic in real code, but resp.StatusCode access }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Handle the edge case where resp is nil and err is nil if tt.resp == nil && tt.err == nil { // This would panic in real code, so we skip the actual test // In production, this should never happen return } result := acceptable(tt.resp, tt.err) assert.Equal(t, tt.expected, result) }) } } func TestAcceptable_RealNetworkTimeout(t *testing.T) { // Create a client with very short timeout client := &http.Client{ Timeout: 1 * time.Nanosecond, // Extremely short timeout to force timeout error } service := NewServiceWithClient("test", client) // Create a server that delays response svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(100 * time.Millisecond) w.WriteHeader(http.StatusOK) })) defer svr.Close() req, err := http.NewRequest(http.MethodGet, svr.URL, nil) assert.NoError(t, err) // This should timeout and trigger the circuit breaker resp, err := service.DoRequest(req) // The error should be present due to timeout assert.Error(t, err) // Response might be nil due to timeout if resp != nil { t.Logf("Response status: %d", resp.StatusCode) } } func TestAcceptable_Integration(t *testing.T) { tests := []struct { name string statusCode int expectBreaker bool // Whether breaker should consider this as failure }{ {"200 OK should not trigger breaker", http.StatusOK, false}, {"201 Created should not trigger breaker", http.StatusCreated, false}, {"400 Bad Request should not trigger breaker", http.StatusBadRequest, false}, {"404 Not Found should not trigger breaker", http.StatusNotFound, false}, {"500 Internal Server Error should trigger breaker", http.StatusInternalServerError, true}, {"502 Bad Gateway should trigger breaker", http.StatusBadGateway, true}, {"503 Service Unavailable should trigger breaker", http.StatusServiceUnavailable, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(tt.statusCode) })) defer svr.Close() service := NewService("test-service-" + tt.name) req, err := http.NewRequest(http.MethodGet, svr.URL, nil) assert.NoError(t, err) resp, err := service.DoRequest(req) assert.NoError(t, err) assert.Equal(t, tt.statusCode, resp.StatusCode) // The actual breaker behavior is tested implicitly through the acceptable function result := acceptable(resp, nil) if tt.expectBreaker { assert.False(t, result, "Status %d should not be acceptable", tt.statusCode) } else { assert.True(t, result, "Status %d should be acceptable", tt.statusCode) } }) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpc/requests_test.go
rest/httpc/requests_test.go
package httpc import ( "context" "net/http" "net/http/httptest" "net/http/httptrace" "strings" "testing" "github.com/stretchr/testify/assert" ztrace "github.com/zeromicro/go-zero/core/trace" "github.com/zeromicro/go-zero/core/trace/tracetest" "github.com/zeromicro/go-zero/rest/httpx" "github.com/zeromicro/go-zero/rest/internal/header" "github.com/zeromicro/go-zero/rest/router" tcodes "go.opentelemetry.io/otel/codes" sdktrace "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/trace" ) func TestDoRequest(t *testing.T) { ztrace.StartAgent(ztrace.Config{ Name: "go-zero-test", Endpoint: "http://localhost:14268", OtlpHttpPath: "/v1/traces", Batcher: "otlphttp", Sampler: 1.0, }) defer ztrace.StopAgent() svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { })) defer svr.Close() req, err := http.NewRequest(http.MethodGet, svr.URL, nil) assert.Nil(t, err) resp, err := DoRequest(req) assert.Nil(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) spanContext := trace.SpanContextFromContext(resp.Request.Context()) assert.True(t, spanContext.IsValid()) } func TestDoRequest_NotFound(t *testing.T) { svr := httptest.NewServer(http.NotFoundHandler()) defer svr.Close() req, err := http.NewRequest(http.MethodPost, svr.URL, nil) assert.Nil(t, err) req.Header.Set(header.ContentType, header.ContentTypeJson) resp, err := DoRequest(req) assert.Nil(t, err) assert.Equal(t, http.StatusNotFound, resp.StatusCode) } func TestDoRequest_Moved(t *testing.T) { svr := httptest.NewServer(http.RedirectHandler("/foo", http.StatusMovedPermanently)) defer svr.Close() req, err := http.NewRequest(http.MethodGet, svr.URL, nil) assert.Nil(t, err) _, err = DoRequest(req) // too many redirects assert.NotNil(t, err) } func TestDo(t *testing.T) { me := tracetest.NewInMemoryExporter(t) type Data struct { Key string `path:"key"` Value int `form:"value"` Header string `header:"X-Header"` Body string `json:"body"` } rt := router.NewRouter() err := rt.Handle(http.MethodPost, "/nodes/:key", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req Data assert.Nil(t, httpx.Parse(r, &req)) })) assert.Nil(t, err) svr := httptest.NewServer(http.HandlerFunc(rt.ServeHTTP)) defer svr.Close() data := Data{ Key: "foo", Value: 10, Header: "my-header", Body: "my body", } resp, err := Do(context.Background(), http.MethodPost, svr.URL+"/nodes/:key", data) assert.Nil(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, 1, len(me.GetSpans())) span := me.GetSpans()[0].Snapshot() assert.Equal(t, sdktrace.Status{ Code: tcodes.Unset, }, span.Status()) assert.Equal(t, 0, len(span.Events())) assert.Equal(t, 7, len(span.Attributes())) } func TestDo_Ptr(t *testing.T) { type Data struct { Key string `path:"key"` Value int `form:"value"` Header string `header:"X-Header"` Body string `json:"body"` } rt := router.NewRouter() err := rt.Handle(http.MethodPost, "/nodes/:key", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req Data assert.Nil(t, httpx.Parse(r, &req)) assert.Equal(t, "foo", req.Key) assert.Equal(t, 10, req.Value) assert.Equal(t, "my-header", req.Header) assert.Equal(t, "my body", req.Body) })) assert.Nil(t, err) svr := httptest.NewServer(http.HandlerFunc(rt.ServeHTTP)) defer svr.Close() data := &Data{ Key: "foo", Value: 10, Header: "my-header", Body: "my body", } resp, err := Do(context.Background(), http.MethodPost, svr.URL+"/nodes/:key", data) assert.Nil(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) } func TestDo_BadRequest(t *testing.T) { _, err := Do(context.Background(), http.MethodPost, ":/nodes/:key", nil) assert.NotNil(t, err) val1 := struct { Value string `json:"value,options=[a,b]"` }{ Value: "c", } _, err = Do(context.Background(), http.MethodPost, "/nodes/:key", val1) assert.NotNil(t, err) val2 := struct { Value string `path:"val"` }{ Value: "", } _, err = Do(context.Background(), http.MethodPost, "/nodes/:key", val2) assert.NotNil(t, err) val3 := struct { Value string `path:"key"` Body string `json:"body"` }{ Value: "foo", } _, err = Do(context.Background(), http.MethodGet, "/nodes/:key", val3) assert.NotNil(t, err) _, err = Do(context.Background(), "\n", "rtmp://nodes", nil) assert.NotNil(t, err) val4 := struct { Value string `path:"val"` }{ Value: "", } _, err = Do(context.Background(), http.MethodPost, "/nodes/:val", val4) assert.NotNil(t, err) val5 := struct { Value string `path:"val"` Another int `path:"foo"` }{ Value: "1", Another: 2, } _, err = Do(context.Background(), http.MethodPost, "/nodes/:val", val5) assert.NotNil(t, err) } func TestDo_Json(t *testing.T) { type Data struct { Key string `path:"key"` Value int `form:"value"` Header string `header:"X-Header"` Body chan int `json:"body"` } rt := router.NewRouter() err := rt.Handle(http.MethodPost, "/nodes/:key", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req Data assert.Nil(t, httpx.Parse(r, &req)) })) assert.Nil(t, err) svr := httptest.NewServer(http.HandlerFunc(rt.ServeHTTP)) defer svr.Close() data := Data{ Key: "foo", Value: 10, Header: "my-header", Body: make(chan int), } _, err = Do(context.Background(), http.MethodPost, svr.URL+"/nodes/:key", data) assert.NotNil(t, err) } func TestDo_WithClientHttpTrace(t *testing.T) { svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) defer svr.Close() enter := false _, err := Do(httptrace.WithClientTrace(context.Background(), &httptrace.ClientTrace{ GetConn: func(hostPort string) { assert.Equal(t, "127.0.0.1", strings.Split(hostPort, ":")[0]) enter = true }, }), http.MethodGet, svr.URL, nil) assert.Nil(t, err) assert.True(t, enter) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpc/requests.go
rest/httpc/requests.go
package httpc import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" nurl "net/url" "strings" "github.com/zeromicro/go-zero/core/lang" "github.com/zeromicro/go-zero/core/mapping" "github.com/zeromicro/go-zero/core/trace" "github.com/zeromicro/go-zero/rest/httpc/internal" "github.com/zeromicro/go-zero/rest/internal/header" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/propagation" semconv "go.opentelemetry.io/otel/semconv/v1.4.0" oteltrace "go.opentelemetry.io/otel/trace" ) var interceptors = []internal.Interceptor{ internal.LogInterceptor, } // Do sends an HTTP request with the given arguments and returns an HTTP response. // data is automatically marshal into a *httpRequest, typically it's defined in an API file. func Do(ctx context.Context, method, url string, data any) (*http.Response, error) { req, err := buildRequest(ctx, method, url, data) if err != nil { return nil, err } return DoRequest(req) } // DoRequest sends an HTTP request and returns an HTTP response. func DoRequest(r *http.Request) (*http.Response, error) { return request(r, defaultClient{}) } type ( client interface { do(r *http.Request) (*http.Response, error) } defaultClient struct{} ) func (c defaultClient) do(r *http.Request) (*http.Response, error) { return http.DefaultClient.Do(r) } func buildFormQuery(u *nurl.URL, val map[string]any) string { query := u.Query() for k, v := range val { query.Add(k, fmt.Sprint(v)) } return query.Encode() } func buildRequest(ctx context.Context, method, url string, data any) (*http.Request, error) { u, err := nurl.Parse(url) if err != nil { return nil, err } var val map[string]map[string]any if data != nil { val, err = mapping.Marshal(data) if err != nil { return nil, err } } if err := fillPath(u, val[pathKey]); err != nil { return nil, err } var reader io.Reader jsonVars, hasJsonBody := val[jsonKey] if hasJsonBody { if method == http.MethodGet { return nil, ErrGetWithBody } var buf bytes.Buffer enc := json.NewEncoder(&buf) if err := enc.Encode(jsonVars); err != nil { return nil, err } reader = &buf } req, err := http.NewRequestWithContext(ctx, method, u.String(), reader) if err != nil { return nil, err } req.URL.RawQuery = buildFormQuery(u, val[formKey]) fillHeader(req, val[headerKey]) if hasJsonBody { req.Header.Set(header.ContentType, header.ContentTypeJson) } return req, nil } func fillHeader(r *http.Request, val map[string]any) { for k, v := range val { r.Header.Add(k, fmt.Sprint(v)) } } func fillPath(u *nurl.URL, val map[string]any) error { used := make(map[string]lang.PlaceholderType) fields := strings.Split(u.Path, slash) for i := range fields { field := fields[i] if len(field) > 0 && field[0] == colon { name := field[1:] ival, ok := val[name] if !ok { return fmt.Errorf("missing path variable %q", name) } value := fmt.Sprint(ival) if len(value) == 0 { return fmt.Errorf("empty path variable %q", name) } fields[i] = value used[name] = lang.Placeholder } } if len(val) != len(used) { for key := range used { delete(val, key) } unused := make([]string, 0, len(val)) for key := range val { unused = append(unused, key) } return fmt.Errorf("more path variables are provided: %q", strings.Join(unused, ", ")) } u.Path = strings.Join(fields, slash) return nil } func request(r *http.Request, cli client) (*http.Response, error) { ctx := r.Context() tracer := trace.TracerFromContext(ctx) propagator := otel.GetTextMapPropagator() spanName := r.URL.Path ctx, span := tracer.Start( ctx, spanName, oteltrace.WithSpanKind(oteltrace.SpanKindClient), oteltrace.WithAttributes(semconv.HTTPClientAttributesFromHTTPRequest(r)...), ) defer span.End() respHandlers := make([]internal.ResponseHandler, len(interceptors)) for i, interceptor := range interceptors { var h internal.ResponseHandler r, h = interceptor(r) respHandlers[i] = h } r = r.WithContext(ctx) propagator.Inject(ctx, propagation.HeaderCarrier(r.Header)) resp, err := cli.do(r) for i := len(respHandlers) - 1; i >= 0; i-- { respHandlers[i](resp, err) } if err != nil { span.RecordError(err) span.SetStatus(codes.Error, err.Error()) return resp, err } span.SetAttributes(semconv.HTTPAttributesFromHTTPStatusCode(resp.StatusCode)...) span.SetStatus(semconv.SpanStatusFromHTTPStatusCodeAndSpanKind(resp.StatusCode, oteltrace.SpanKindClient)) return resp, err }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpc/responses.go
rest/httpc/responses.go
package httpc import ( "bytes" "io" "net/http" "strings" "github.com/zeromicro/go-zero/core/mapping" "github.com/zeromicro/go-zero/rest/internal/encoding" "github.com/zeromicro/go-zero/rest/internal/header" ) // Parse parses the response. func Parse(resp *http.Response, val any) error { if err := ParseHeaders(resp, val); err != nil { return err } return ParseJsonBody(resp, val) } // ParseHeaders parses the response headers. func ParseHeaders(resp *http.Response, val any) error { return encoding.ParseHeaders(resp.Header, val) } // ParseJsonBody parses the response body, which should be in json content type. func ParseJsonBody(resp *http.Response, val any) error { defer resp.Body.Close() if isContentTypeJson(resp) { if resp.ContentLength > 0 { return mapping.UnmarshalJsonReader(resp.Body, val) } var buf bytes.Buffer if _, err := io.Copy(&buf, resp.Body); err != nil { return err } if buf.Len() > 0 { return mapping.UnmarshalJsonReader(&buf, val) } } return mapping.UnmarshalJsonMap(nil, val) } func isContentTypeJson(r *http.Response) bool { return strings.Contains(r.Header.Get(header.ContentType), header.ApplicationJson) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpc/vars.go
rest/httpc/vars.go
package httpc import "errors" const ( pathKey = "path" formKey = "form" headerKey = "header" jsonKey = "json" slash = "/" colon = ':' ) // ErrGetWithBody indicates that GET request with body. var ErrGetWithBody = errors.New("HTTP GET should not have body")
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpc/responses_test.go
rest/httpc/responses_test.go
package httpc import ( "errors" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/rest/internal/header" ) func TestParse(t *testing.T) { var val struct { Foo string `header:"foo"` Name string `json:"name"` Value int `json:"value"` } svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("foo", "bar") w.Header().Set(header.ContentType, header.ContentTypeJson) w.Write([]byte(`{"name":"kevin","value":100}`)) })) defer svr.Close() req, err := http.NewRequest(http.MethodGet, svr.URL, nil) assert.Nil(t, err) resp, err := DoRequest(req) assert.Nil(t, err) assert.Nil(t, Parse(resp, &val)) assert.Equal(t, "bar", val.Foo) assert.Equal(t, "kevin", val.Name) assert.Equal(t, 100, val.Value) } func TestParseHeaderError(t *testing.T) { var val struct { Foo int `header:"foo"` } svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("foo", "bar") w.Header().Set(header.ContentType, header.ContentTypeJson) })) defer svr.Close() req, err := http.NewRequest(http.MethodGet, svr.URL, nil) assert.Nil(t, err) resp, err := DoRequest(req) assert.Nil(t, err) assert.NotNil(t, Parse(resp, &val)) } func TestParseNoBody(t *testing.T) { var val struct { Foo string `header:"foo"` } svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("foo", "bar") w.Header().Set(header.ContentType, header.ContentTypeJson) })) defer svr.Close() req, err := http.NewRequest(http.MethodGet, svr.URL, nil) assert.Nil(t, err) resp, err := DoRequest(req) assert.Nil(t, err) assert.Nil(t, Parse(resp, &val)) assert.Equal(t, "bar", val.Foo) } func TestParseWithZeroValue(t *testing.T) { var val struct { Foo int `header:"foo"` Bar int `json:"bar"` } svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("foo", "0") w.Header().Set(header.ContentType, header.ContentTypeJson) w.Write([]byte(`{"bar":0}`)) })) defer svr.Close() req, err := http.NewRequest(http.MethodGet, svr.URL, nil) assert.Nil(t, err) resp, err := DoRequest(req) assert.Nil(t, err) assert.Nil(t, Parse(resp, &val)) assert.Equal(t, 0, val.Foo) assert.Equal(t, 0, val.Bar) } func TestParseWithNegativeContentLength(t *testing.T) { var val struct { Bar int `json:"bar"` } svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set(header.ContentType, header.ContentTypeJson) w.Write([]byte(`{"bar":0}`)) })) defer svr.Close() req, err := http.NewRequest(http.MethodGet, svr.URL, nil) assert.Nil(t, err) tests := []struct { name string length int64 }{ { name: "negative", length: -1, }, { name: "zero", length: 0, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { resp, err := DoRequest(req) resp.ContentLength = test.length assert.Nil(t, err) assert.Nil(t, Parse(resp, &val)) assert.Equal(t, 0, val.Bar) }) } } func TestParseWithNegativeContentLengthNoBody(t *testing.T) { var val struct{} svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set(header.ContentType, header.ContentTypeJson) })) defer svr.Close() req, err := http.NewRequest(http.MethodGet, svr.URL, nil) assert.Nil(t, err) tests := []struct { name string length int64 }{ { name: "negative", length: -1, }, { name: "zero", length: 0, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { resp, err := DoRequest(req) resp.ContentLength = test.length assert.Nil(t, err) assert.Nil(t, Parse(resp, &val)) }) } } func TestParseJsonBody_BodyError(t *testing.T) { var val struct{} svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set(header.ContentType, header.ContentTypeJson) })) defer svr.Close() req, err := http.NewRequest(http.MethodGet, svr.URL, nil) assert.Nil(t, err) resp, err := DoRequest(req) resp.ContentLength = -1 resp.Body = mockedReader{} assert.Nil(t, err) assert.NotNil(t, Parse(resp, &val)) } type mockedReader struct{} func (m mockedReader) Close() error { return nil } func (m mockedReader) Read(_ []byte) (n int, err error) { return 0, errors.New("dummy") }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpc/internal/interceptor.go
rest/httpc/internal/interceptor.go
package internal import "net/http" type ( Interceptor func(r *http.Request) (*http.Request, ResponseHandler) ResponseHandler func(resp *http.Response, err error) )
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpc/internal/metricsinterceptor.go
rest/httpc/internal/metricsinterceptor.go
package internal import ( "net/http" "net/url" "strconv" "time" "github.com/zeromicro/go-zero/core/metric" "github.com/zeromicro/go-zero/core/timex" ) const clientNamespace = "httpc_client" var ( MetricClientReqDur = metric.NewHistogramVec(&metric.HistogramVecOpts{ Namespace: clientNamespace, Subsystem: "requests", Name: "duration_ms", Help: "http client requests duration(ms).", Labels: []string{"name", "method", "url"}, Buckets: []float64{0.25, 0.5, 1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2000, 5000, 10000, 15000}, }) MetricClientReqCodeTotal = metric.NewCounterVec(&metric.CounterVecOpts{ Namespace: clientNamespace, Subsystem: "requests", Name: "code_total", Help: "http client requests code count.", Labels: []string{"name", "method", "url", "code"}, }) ) type MetricsURLRewriter func(u url.URL) string func MetricsInterceptor(name string, pr MetricsURLRewriter) Interceptor { return func(r *http.Request) (*http.Request, ResponseHandler) { startTime := timex.Now() return r, func(resp *http.Response, err error) { var code int var path string // error or resp is nil, set code=500 if err != nil || resp == nil { code = http.StatusInternalServerError } else { code = resp.StatusCode } u := cleanURL(*r.URL) method := r.Method if pr != nil { path = pr(u) } else { path = u.String() } MetricClientReqDur.ObserveFloat(float64(timex.Since(startTime))/float64(time.Millisecond), name, method, path) MetricClientReqCodeTotal.Inc(name, method, path, strconv.Itoa(code)) } } } func cleanURL(r url.URL) url.URL { r.RawQuery = "" r.RawFragment = "" r.User = nil return r }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpc/internal/loginterceptor_test.go
rest/httpc/internal/loginterceptor_test.go
package internal import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestLogInterceptor(t *testing.T) { svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { })) defer svr.Close() req, err := http.NewRequest(http.MethodGet, svr.URL, nil) assert.Nil(t, err) req, handler := LogInterceptor(req) resp, err := http.DefaultClient.Do(req) handler(resp, err) assert.Nil(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) } func TestLogInterceptorServerError(t *testing.T) { svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) })) defer svr.Close() req, err := http.NewRequest(http.MethodGet, svr.URL, nil) assert.Nil(t, err) req, handler := LogInterceptor(req) resp, err := http.DefaultClient.Do(req) handler(resp, err) assert.Nil(t, err) assert.Equal(t, http.StatusInternalServerError, resp.StatusCode) } func TestLogInterceptorServerClosed(t *testing.T) { svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) })) defer svr.Close() req, err := http.NewRequest(http.MethodGet, svr.URL, nil) assert.Nil(t, err) svr.Close() req, handler := LogInterceptor(req) resp, err := http.DefaultClient.Do(req) handler(resp, err) assert.NotNil(t, err) assert.Nil(t, resp) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpc/internal/metricsinterceptor_test.go
rest/httpc/internal/metricsinterceptor_test.go
package internal import ( "net/http" "net/http/httptest" "testing" "time" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/logx" ) func TestMetricsInterceptor(t *testing.T) { logx.Disable() svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(100 * time.Millisecond) w.WriteHeader(http.StatusInternalServerError) })) defer svr.Close() req, err := http.NewRequest(http.MethodGet, svr.URL, nil) assert.NotNil(t, req) assert.Nil(t, err) interceptor := MetricsInterceptor("test", nil) req, handler := interceptor(req) resp, err := http.DefaultClient.Do(req) assert.NotNil(t, resp) assert.Nil(t, err) handler(resp, err) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpc/internal/loginterceptor.go
rest/httpc/internal/loginterceptor.go
package internal import ( "net/http" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/timex" "go.opentelemetry.io/otel/propagation" ) func LogInterceptor(r *http.Request) (*http.Request, ResponseHandler) { start := timex.Now() return r, func(resp *http.Response, err error) { duration := timex.Since(start) if err != nil { logger := logx.WithContext(r.Context()).WithDuration(duration) logger.Errorf("[HTTP] %s %s - %v", r.Method, r.URL, err) return } var tc propagation.TraceContext ctx := tc.Extract(r.Context(), propagation.HeaderCarrier(resp.Header)) logger := logx.WithContext(ctx).WithDuration(duration) if isOkResponse(resp.StatusCode) { logger.Infof("[HTTP] %d - %s %s", resp.StatusCode, r.Method, r.URL) } else { logger.Errorf("[HTTP] %d - %s %s", resp.StatusCode, r.Method, r.URL) } } } func isOkResponse(code int) bool { return code < http.StatusBadRequest }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpx/router.go
rest/httpx/router.go
package httpx import "net/http" // Router interface represents a http router that handles http requests. type Router interface { http.Handler Handle(method, path string, handler http.Handler) error SetNotFoundHandler(handler http.Handler) SetNotAllowedHandler(handler http.Handler) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpx/util.go
rest/httpx/util.go
package httpx import ( "errors" "fmt" "net/http" "strings" ) const ( xForwardedFor = "X-Forwarded-For" arraySuffix = "[]" // most servers and clients have a limit of 8192 bytes (8 KB) // one parameter at least take 4 chars, for example `?a=b&c=d` maxFormParamCount = 2048 ) // GetFormValues returns the form values supporting three array notation formats: // 1. Standard notation: /api?names=alice&names=bob // 2. Comma notation: /api?names=alice,bob // 3. Bracket notation: /api?names[]=alice&names[]=bob func GetFormValues(r *http.Request) (map[string]any, error) { if err := r.ParseForm(); err != nil { return nil, err } if err := r.ParseMultipartForm(maxMemory); err != nil { if !errors.Is(err, http.ErrNotMultipart) { return nil, err } } var n int params := make(map[string]any, len(r.Form)) for name, values := range r.Form { filtered := make([]string, 0, len(values)) for _, v := range values { // ignore empty values, especially for optional int parameters // e.g. /api?ids= // e.g. /api // type Req struct { // IDs []int `form:"ids,optional"` // } if len(v) == 0 { continue } if n < maxFormParamCount { filtered = append(filtered, v) n++ } else { return nil, fmt.Errorf("too many form values, error: %s", r.Form.Encode()) } } if len(filtered) > 0 { if strings.HasSuffix(name, arraySuffix) { name = name[:len(name)-2] } params[name] = filtered } } return params, nil } // GetRemoteAddr returns the peer address, supports X-Forward-For. func GetRemoteAddr(r *http.Request) string { v := r.Header.Get(xForwardedFor) if len(v) > 0 { return v } return r.RemoteAddr }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpx/requests_test.go
rest/httpx/requests_test.go
package httpx import ( "bytes" "encoding/json" "errors" "net/http" "net/http/httptest" "reflect" "strconv" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/rest/internal/header" "github.com/zeromicro/go-zero/rest/pathvar" ) func TestParseForm(t *testing.T) { t.Run("slice", func(t *testing.T) { var v struct { Name string `form:"name"` Age int `form:"age"` Percent float64 `form:"percent,optional"` } r, err := http.NewRequest( http.MethodGet, "/a?name=hello&age=18&percent=3.4", http.NoBody) assert.Nil(t, err) assert.Nil(t, Parse(r, &v)) assert.Equal(t, "hello", v.Name) assert.Equal(t, 18, v.Age) assert.Equal(t, 3.4, v.Percent) }) t.Run("no value", func(t *testing.T) { var v struct { NoValue string `form:"noValue,optional"` } r, err := http.NewRequest( http.MethodGet, "/a?name=hello&age=18&percent=3.4&statuses=try&statuses=done&singleValue=one", http.NoBody) assert.Nil(t, err) assert.Nil(t, Parse(r, &v)) assert.Equal(t, 0, len(v.NoValue)) }) t.Run("slice with one value on array format", func(t *testing.T) { var v struct { Names string `form:"names"` } r, err := http.NewRequest( http.MethodGet, "/a?names=1,2,3", http.NoBody) assert.NoError(t, err) if assert.NoError(t, Parse(r, &v)) { assert.Equal(t, "1,2,3", v.Names) } }) } func TestParseFormArray(t *testing.T) { t.Run("slice", func(t *testing.T) { var v struct { Name []string `form:"name"` Age []int `form:"age"` Percent []float64 `form:"percent,optional"` } r, err := http.NewRequest( http.MethodGet, "/a?name=hello&name=world&age=18&age=19&percent=3.4&percent=4.5", http.NoBody) assert.NoError(t, err) if assert.NoError(t, Parse(r, &v)) { assert.ElementsMatch(t, []string{"hello", "world"}, v.Name) assert.ElementsMatch(t, []int{18, 19}, v.Age) assert.ElementsMatch(t, []float64{3.4, 4.5}, v.Percent) } }) t.Run("slice with single value", func(t *testing.T) { var v struct { Name []string `form:"name"` Age []int `form:"age"` Percent []float64 `form:"percent,optional"` } r, err := http.NewRequest( http.MethodGet, "/a?name=hello&age=18&percent=3.4", http.NoBody) assert.NoError(t, err) if assert.NoError(t, Parse(r, &v)) { assert.ElementsMatch(t, []string{"hello"}, v.Name) assert.ElementsMatch(t, []int{18}, v.Age) assert.ElementsMatch(t, []float64{3.4}, v.Percent) } }) t.Run("slice with empty", func(t *testing.T) { var v struct { Name []string `form:"name,optional"` } r, err := http.NewRequest( http.MethodGet, "/a", http.NoBody) assert.NoError(t, err) if assert.NoError(t, Parse(r, &v)) { assert.ElementsMatch(t, []string{}, v.Name) } }) t.Run("slice with empty", func(t *testing.T) { var v struct { Name []string `form:"name,optional"` } r, err := http.NewRequest( http.MethodGet, "/a?name=", http.NoBody) assert.NoError(t, err) if assert.NoError(t, Parse(r, &v)) { assert.Empty(t, v.Name) } }) t.Run("slice with empty and non-empty", func(t *testing.T) { var v struct { Name []string `form:"name"` } r, err := http.NewRequest( http.MethodGet, "/a?name=&name=1", http.NoBody) assert.NoError(t, err) if assert.NoError(t, Parse(r, &v)) { assert.ElementsMatch(t, []string{"1"}, v.Name) } }) t.Run("slice with one value on array format", func(t *testing.T) { var v struct { Names []string `form:"names"` } r, err := http.NewRequest( http.MethodGet, "/a?names=1,2,3", http.NoBody) assert.NoError(t, err) if assert.NoError(t, Parse(r, &v)) { assert.ElementsMatch(t, []string{"1,2,3"}, v.Names) } }) t.Run("slice with one value on combined array format", func(t *testing.T) { var v struct { Names []string `form:"names"` } r, err := http.NewRequest( http.MethodGet, "/a?names=[1,2,3]&names=4", http.NoBody) assert.NoError(t, err) if assert.NoError(t, Parse(r, &v)) { assert.ElementsMatch(t, []string{"[1,2,3]", "4"}, v.Names) } }) t.Run("slice with one value on integer array format", func(t *testing.T) { var v struct { Numbers []int `form:"numbers"` } r, err := http.NewRequest( http.MethodGet, "/a?numbers=1,2,3", http.NoBody) assert.NoError(t, err) assert.Error(t, Parse(r, &v)) }) t.Run("slice with one value on array format brackets", func(t *testing.T) { var v struct { Names []string `form:"names"` } r, err := http.NewRequest( http.MethodGet, "/a?names[]=1&names[]=2&names[]=3", http.NoBody) assert.NoError(t, err) if assert.NoError(t, Parse(r, &v)) { assert.ElementsMatch(t, []string{"1", "2", "3"}, v.Names) } }) t.Run("slice with one empty value on integer array format", func(t *testing.T) { var v struct { Numbers []int `form:"numbers,optional"` } r, err := http.NewRequest( http.MethodGet, "/a?numbers=", http.NoBody) assert.NoError(t, err) if assert.NoError(t, Parse(r, &v)) { assert.Empty(t, v.Numbers) } }) t.Run("slice with one value on integer array format", func(t *testing.T) { var v struct { Numbers []int `form:"numbers,optional"` } r, err := http.NewRequest( http.MethodGet, "/a?numbers=&numbers=2", http.NoBody) assert.NoError(t, err) if assert.NoError(t, Parse(r, &v)) { assert.ElementsMatch(t, []int{2}, v.Numbers) } }) t.Run("slice with one empty value on float64 array format", func(t *testing.T) { var v struct { Numbers []float64 `form:"numbers,optional"` } r, err := http.NewRequest( http.MethodGet, "/a?numbers=", http.NoBody) assert.NoError(t, err) if assert.NoError(t, Parse(r, &v)) { assert.Empty(t, v.Numbers) } }) t.Run("slice with one value on float64 array format", func(t *testing.T) { var v struct { Numbers []float64 `form:"numbers,optional"` } r, err := http.NewRequest( http.MethodGet, "/a?numbers=&numbers=2", http.NoBody) assert.NoError(t, err) if assert.NoError(t, Parse(r, &v)) { assert.ElementsMatch(t, []float64{2}, v.Numbers) } }) t.Run("slice with one value", func(t *testing.T) { var v struct { Codes []string `form:"codes"` } r, err := http.NewRequest( http.MethodGet, "/a?codes=aaa,bbb,ccc", http.NoBody) assert.NoError(t, err) if assert.NoError(t, Parse(r, &v)) { assert.ElementsMatch(t, []string{"aaa,bbb,ccc"}, v.Codes) } }) t.Run("slice with multiple values", func(t *testing.T) { var v struct { Codes []string `form:"codes,arrayComma=false"` } r, err := http.NewRequest( http.MethodGet, "/a?codes=aaa,bbb,ccc&codes=ccc,ddd,eee", http.NoBody) assert.NoError(t, err) if assert.NoError(t, Parse(r, &v)) { assert.ElementsMatch(t, []string{"aaa,bbb,ccc", "ccc,ddd,eee"}, v.Codes) } }) } func TestParseForm_Error(t *testing.T) { var v struct { Name string `form:"name"` Age int `form:"age"` } r := httptest.NewRequest(http.MethodGet, "/a?name=hello;", http.NoBody) assert.NotNil(t, ParseForm(r, &v)) } func TestParseHeader(t *testing.T) { tests := []struct { name string value string expect map[string]string }{ { name: "empty", value: "", expect: map[string]string{}, }, { name: "regular", value: "key=value", expect: map[string]string{"key": "value"}, }, { name: "next empty", value: "key=value;", expect: map[string]string{"key": "value"}, }, { name: "regular", value: "key=value;foo", expect: map[string]string{"key": "value"}, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { t.Parallel() m := ParseHeader(test.value) assert.EqualValues(t, test.expect, m) }) } } func TestParsePath(t *testing.T) { var v struct { Name string `path:"name"` Age int `path:"age"` } r := httptest.NewRequest(http.MethodGet, "/", http.NoBody) r = pathvar.WithVars(r, map[string]string{ "name": "foo", "age": "18", }) err := Parse(r, &v) assert.Nil(t, err) assert.Equal(t, "foo", v.Name) assert.Equal(t, 18, v.Age) } func TestParsePath_Error(t *testing.T) { var v struct { Name string `path:"name"` Age int `path:"age"` } r := httptest.NewRequest(http.MethodGet, "/", http.NoBody) r = pathvar.WithVars(r, map[string]string{ "name": "foo", }) assert.NotNil(t, Parse(r, &v)) } func TestParseFormOutOfRange(t *testing.T) { var v struct { Age int `form:"age,range=[10:20)"` } tests := []struct { url string pass bool }{ { url: "/a?age=5", pass: false, }, { url: "/a?age=10", pass: true, }, { url: "/a?age=15", pass: true, }, { url: "/a?age=20", pass: false, }, { url: "/a?age=28", pass: false, }, } for _, test := range tests { r, err := http.NewRequest(http.MethodGet, test.url, http.NoBody) assert.Nil(t, err) err = Parse(r, &v) if test.pass { assert.Nil(t, err) } else { assert.NotNil(t, err) } } } func TestParseMultipartForm(t *testing.T) { var v struct { Name string `form:"name"` Age int `form:"age"` } body := strings.Replace(`----------------------------220477612388154780019383 Content-Disposition: form-data; name="name" kevin ----------------------------220477612388154780019383 Content-Disposition: form-data; name="age" 18 ----------------------------220477612388154780019383--`, "\n", "\r\n", -1) r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body)) r.Header.Set(ContentType, "multipart/form-data; boundary=--------------------------220477612388154780019383") assert.Nil(t, Parse(r, &v)) assert.Equal(t, "kevin", v.Name) assert.Equal(t, 18, v.Age) } func TestParseMultipartFormWrongBoundary(t *testing.T) { var v struct { Name string `form:"name"` Age int `form:"age"` } body := strings.Replace(`----------------------------22047761238815478001938 Content-Disposition: form-data; name="name" kevin ----------------------------22047761238815478001938 Content-Disposition: form-data; name="age" 18 ----------------------------22047761238815478001938--`, "\n", "\r\n", -1) r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body)) r.Header.Set(ContentType, "multipart/form-data; boundary=--------------------------220477612388154780019383") assert.NotNil(t, Parse(r, &v)) } func TestParseJsonBody(t *testing.T) { t.Run("has body", func(t *testing.T) { var v struct { Name string `json:"name"` Age int `json:"age"` } body := `{"name":"kevin", "age": 18}` r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body)) r.Header.Set(ContentType, header.ContentTypeJson) if assert.NoError(t, Parse(r, &v)) { assert.Equal(t, "kevin", v.Name) assert.Equal(t, 18, v.Age) } }) t.Run("bad body", func(t *testing.T) { var v struct { Name string `json:"name"` Age int `json:"age"` } body := `{"name":"kevin", "ag": 18}` r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body)) r.Header.Set(ContentType, header.ContentTypeJson) assert.Error(t, Parse(r, &v)) }) t.Run("hasn't body", func(t *testing.T) { var v struct { Name string `json:"name,optional"` Age int `json:"age,optional"` } r := httptest.NewRequest(http.MethodGet, "/", http.NoBody) assert.Nil(t, Parse(r, &v)) assert.Equal(t, "", v.Name) assert.Equal(t, 0, v.Age) }) t.Run("array body", func(t *testing.T) { var v []struct { Name string `json:"name"` Age int `json:"age"` } body := `[{"name":"kevin", "age": 18}]` r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body)) r.Header.Set(ContentType, header.ContentTypeJson) assert.NoError(t, Parse(r, &v)) assert.Equal(t, 1, len(v)) assert.Equal(t, "kevin", v[0].Name) assert.Equal(t, 18, v[0].Age) }) t.Run("form and array body", func(t *testing.T) { var v []struct { // we can only ignore the form tag, // because if the value is a slice, it should be in the body, // but it's hard to detect when we treat it as a json body. Product string `form:"product"` Name string `json:"name"` Age int `json:"age"` } body := `[{"name":"apple", "age": 18}]` r := httptest.NewRequest(http.MethodPost, "/a?product=tree", strings.NewReader(body)) r.Header.Set(ContentType, header.ContentTypeJson) assert.NoError(t, Parse(r, &v)) assert.Equal(t, 1, len(v)) assert.Equal(t, "apple", v[0].Name) assert.Equal(t, 18, v[0].Age) }) t.Run("bytes field", func(t *testing.T) { type v struct { Signature []byte `json:"signature,optional"` } v1 := v{ Signature: []byte{0x01, 0xff, 0x00}, } body, _ := json.Marshal(v1) t.Logf("body:%s", string(body)) r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(string(body))) r.Header.Set(ContentType, header.ContentTypeJson) var v2 v err := ParseJsonBody(r, &v2) if assert.NoError(t, err) { assert.Greater(t, len(v2.Signature), 0) } t.Logf("%x", v2.Signature) assert.EqualValues(t, v1.Signature, v2.Signature) }) } func TestParseRequired(t *testing.T) { v := struct { Name string `form:"name"` Percent float64 `form:"percent"` }{} r, err := http.NewRequest(http.MethodGet, "/a?name=hello", http.NoBody) assert.Nil(t, err) assert.NotNil(t, Parse(r, &v)) } func TestParseOptions(t *testing.T) { v := struct { Position int8 `form:"pos,options=1|2"` }{} r, err := http.NewRequest(http.MethodGet, "/a?pos=4", http.NoBody) assert.Nil(t, err) assert.NotNil(t, Parse(r, &v)) } func TestParseHeaders(t *testing.T) { type AnonymousStruct struct { XRealIP string `header:"x-real-ip"` Accept string `header:"Accept,optional"` } v := struct { Name string `header:"name,optional"` Percent string `header:"percent"` Addrs []string `header:"addrs"` XForwardedFor string `header:"X-Forwarded-For,optional"` AnonymousStruct }{} request, err := http.NewRequest("POST", "/", http.NoBody) if err != nil { t.Fatal(err) } request.Header.Set("name", "chenquan") request.Header.Set("percent", "1") request.Header.Add("addrs", "addr1") request.Header.Add("addrs", "addr2") request.Header.Add("X-Forwarded-For", "10.0.10.11") request.Header.Add("x-real-ip", "10.0.11.10") request.Header.Add("Accept", header.ContentTypeJson) err = ParseHeaders(request, &v) if err != nil { t.Fatal(err) } assert.Equal(t, "chenquan", v.Name) assert.Equal(t, "1", v.Percent) assert.Equal(t, []string{"addr1", "addr2"}, v.Addrs) assert.Equal(t, "10.0.10.11", v.XForwardedFor) assert.Equal(t, "10.0.11.10", v.XRealIP) assert.Equal(t, header.ContentTypeJson, v.Accept) } func TestParseHeaders_Error(t *testing.T) { v := struct { Name string `header:"name"` Age int `header:"age"` }{} r := httptest.NewRequest("POST", "/", http.NoBody) r.Header.Set("name", "foo") assert.NotNil(t, Parse(r, &v)) } func TestParseWithValidator(t *testing.T) { SetValidator(mockValidator{}) defer SetValidator(mockValidator{nop: true}) var v struct { Name string `form:"name"` Age int `form:"age"` Percent float64 `form:"percent,optional"` } r, err := http.NewRequest(http.MethodGet, "/a?name=hello&age=18&percent=3.4", http.NoBody) assert.Nil(t, err) if assert.NoError(t, Parse(r, &v)) { assert.Equal(t, "hello", v.Name) assert.Equal(t, 18, v.Age) assert.Equal(t, 3.4, v.Percent) } } func TestParseWithValidatorWithError(t *testing.T) { SetValidator(mockValidator{}) defer SetValidator(mockValidator{nop: true}) var v struct { Name string `form:"name"` Age int `form:"age"` Percent float64 `form:"percent,optional"` } r, err := http.NewRequest(http.MethodGet, "/a?name=world&age=18&percent=3.4", http.NoBody) assert.Nil(t, err) assert.Error(t, Parse(r, &v)) } func TestParseWithValidatorRequest(t *testing.T) { SetValidator(mockValidator{}) defer SetValidator(mockValidator{nop: true}) var v mockRequest r, err := http.NewRequest(http.MethodGet, "/a?&age=18", http.NoBody) assert.Nil(t, err) assert.Error(t, Parse(r, &v)) } func TestParseFormWithDot(t *testing.T) { var v struct { Age int `form:"user.age"` } r, err := http.NewRequest(http.MethodGet, "/a?user.age=18", http.NoBody) assert.Nil(t, err) assert.NoError(t, Parse(r, &v)) assert.Equal(t, 18, v.Age) } func TestParsePathWithDot(t *testing.T) { var v struct { Name string `path:"name.val"` Age int `path:"age.val"` } r := httptest.NewRequest(http.MethodGet, "/", http.NoBody) r = pathvar.WithVars(r, map[string]string{ "name.val": "foo", "age.val": "18", }) err := Parse(r, &v) assert.Nil(t, err) assert.Equal(t, "foo", v.Name) assert.Equal(t, 18, v.Age) } func TestParseWithFloatPtr(t *testing.T) { t.Run("has float32 pointer", func(t *testing.T) { var v struct { WeightFloat32 *float32 `json:"weightFloat32,optional"` } body := `{"weightFloat32": 3.2}` r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body)) r.Header.Set(ContentType, header.ContentTypeJson) if assert.NoError(t, Parse(r, &v)) { assert.Equal(t, float32(3.2), *v.WeightFloat32) } }) } func TestParseWithEscapedParams(t *testing.T) { t.Run("escaped", func(t *testing.T) { var v struct { Dev string `form:"dev"` } r := httptest.NewRequest(http.MethodGet, "http://127.0.0.1/api/v2/dev/test?dev=se205%5fy1205%5fj109%26verRelease=v01%26iid1=863494061186673%26iid2=863494061186681%26mcc=636%26mnc=1", http.NoBody) if assert.NoError(t, Parse(r, &v)) { assert.Equal(t, "se205_y1205_j109&verRelease=v01&iid1=863494061186673&iid2=863494061186681&mcc=636&mnc=1", v.Dev) } }) } func TestCustomUnmarshalerStructRequest(t *testing.T) { reqBody := `{"name": "hello"}` r := httptest.NewRequest(http.MethodPost, "/a", bytes.NewReader([]byte(reqBody))) r.Header.Set(ContentType, JsonContentType) v := struct { Foo *mockUnmarshaler `json:"name"` }{} assert.Nil(t, Parse(r, &v)) assert.Equal(t, "hello", v.Foo.Name) } func TestParseJsonStringRequest(t *testing.T) { type GoodsInfo struct { Sku int64 `json:"sku,optional"` } type GetReq struct { GoodsList []*GoodsInfo `json:"goods_list"` } input := `{"goods_list":"[{\"sku\":11},{\"sku\":22}]"}` r := httptest.NewRequest(http.MethodPost, "/a", strings.NewReader(input)) r.Header.Set(ContentType, JsonContentType) var v GetReq assert.NotPanics(t, func() { assert.NoError(t, Parse(r, &v)) assert.Equal(t, 2, len(v.GoodsList)) assert.ElementsMatch(t, []int64{11, 22}, []int64{v.GoodsList[0].Sku, v.GoodsList[1].Sku}) }) } type valid1 struct{} func (v valid1) Validate(*http.Request, any) error { return nil } type valid2 struct{} func (v valid2) Validate(*http.Request, any) error { return nil } func TestSetValidatorTwice(t *testing.T) { // panic: sync/atomic: store of inconsistently typed value into Value assert.NotPanics(t, func() { SetValidator(valid1{}) SetValidator(valid2{}) }) } func BenchmarkParseRaw(b *testing.B) { r, err := http.NewRequest(http.MethodGet, "http://hello.com/a?name=hello&age=18&percent=3.4", http.NoBody) if err != nil { b.Fatal(err) } for i := 0; i < b.N; i++ { v := struct { Name string `form:"name"` Age int `form:"age"` Percent float64 `form:"percent,optional"` }{} v.Name = r.FormValue("name") v.Age, err = strconv.Atoi(r.FormValue("age")) if err != nil { b.Fatal(err) } v.Percent, err = strconv.ParseFloat(r.FormValue("percent"), 64) if err != nil { b.Fatal(err) } } } func BenchmarkParseAuto(b *testing.B) { r, err := http.NewRequest(http.MethodGet, "http://hello.com/a?name=hello&age=18&percent=3.4", http.NoBody) if err != nil { b.Fatal(err) } for i := 0; i < b.N; i++ { v := struct { Name string `form:"name"` Age int `form:"age"` Percent float64 `form:"percent,optional"` }{} if err = Parse(r, &v); err != nil { b.Fatal(err) } } } type mockValidator struct { nop bool } func (m mockValidator) Validate(r *http.Request, data any) error { if m.nop { return nil } if r.URL.Path == "/a" { val := reflect.ValueOf(data).Elem().FieldByName("Name").String() if val != "hello" { return errors.New("name is not hello") } } return nil } type mockRequest struct { Name string `json:"name,optional"` } func (m mockRequest) Validate() error { if m.Name != "hello" { return errors.New("name is not hello") } return nil } type mockUnmarshaler struct { Name string } func (m *mockUnmarshaler) UnmarshalJSON(b []byte) error { m.Name = string(b) return nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpx/requests.go
rest/httpx/requests.go
package httpx import ( "io" "net/http" "reflect" "strings" "sync" "github.com/zeromicro/go-zero/core/mapping" "github.com/zeromicro/go-zero/core/validation" "github.com/zeromicro/go-zero/rest/internal/encoding" "github.com/zeromicro/go-zero/rest/internal/header" "github.com/zeromicro/go-zero/rest/pathvar" ) const ( formKey = "form" pathKey = "path" maxMemory = 32 << 20 // 32MB maxBodyLen = 8 << 20 // 8MB separator = ";" tokensInAttribute = 2 ) var ( formUnmarshaler = mapping.NewUnmarshaler( formKey, mapping.WithStringValues(), mapping.WithOpaqueKeys(), mapping.WithFromArray()) pathUnmarshaler = mapping.NewUnmarshaler( pathKey, mapping.WithStringValues(), mapping.WithOpaqueKeys()) // panic: sync/atomic: store of inconsistently typed value into Value // don't use atomic.Value to store the validator, different concrete types still panic validator Validator validatorLock sync.RWMutex ) // Validator defines the interface for validating the request. type Validator interface { // Validate validates the request and parsed data. Validate(r *http.Request, data any) error } // Parse parses the request. func Parse(r *http.Request, v any) error { kind := mapping.Deref(reflect.TypeOf(v)).Kind() if kind != reflect.Array && kind != reflect.Slice { if err := ParsePath(r, v); err != nil { return err } if err := ParseForm(r, v); err != nil { return err } if err := ParseHeaders(r, v); err != nil { return err } } if err := ParseJsonBody(r, v); err != nil { return err } if valid, ok := v.(validation.Validator); ok { return valid.Validate() } else if val := getValidator(); val != nil { return val.Validate(r, v) } return nil } // ParseHeaders parses the headers request. func ParseHeaders(r *http.Request, v any) error { return encoding.ParseHeaders(r.Header, v) } // ParseForm parses the form request. func ParseForm(r *http.Request, v any) error { params, err := GetFormValues(r) if err != nil { return err } return formUnmarshaler.Unmarshal(params, v) } // ParseHeader parses the request header and returns a map. func ParseHeader(headerValue string) map[string]string { ret := make(map[string]string) fields := strings.Split(headerValue, separator) for _, field := range fields { field = strings.TrimSpace(field) if len(field) == 0 { continue } kv := strings.SplitN(field, "=", tokensInAttribute) if len(kv) != tokensInAttribute { continue } ret[kv[0]] = kv[1] } return ret } // ParseJsonBody parses the post request which contains json in body. func ParseJsonBody(r *http.Request, v any) error { if withJsonBody(r) { reader := io.LimitReader(r.Body, maxBodyLen) return mapping.UnmarshalJsonReader(reader, v) } return mapping.UnmarshalJsonMap(nil, v) } // ParsePath parses the symbols reside in url path. // Like http://localhost/bag/:name func ParsePath(r *http.Request, v any) error { vars := pathvar.Vars(r) m := make(map[string]any, len(vars)) for k, v := range vars { m[k] = v } return pathUnmarshaler.Unmarshal(m, v) } // SetValidator sets the validator. // The validator is used to validate the request, only called in Parse, // not in ParseHeaders, ParseForm, ParseHeader, ParseJsonBody, ParsePath. func SetValidator(val Validator) { validatorLock.Lock() defer validatorLock.Unlock() validator = val } func getValidator() Validator { validatorLock.RLock() defer validatorLock.RUnlock() return validator } func withJsonBody(r *http.Request) bool { return r.ContentLength > 0 && strings.Contains(r.Header.Get(header.ContentType), header.ApplicationJson) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpx/responses.go
rest/httpx/responses.go
package httpx import ( "context" "errors" "fmt" "io" "net/http" "sync" "github.com/zeromicro/go-zero/core/jsonx" "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/rest/internal/errcode" "github.com/zeromicro/go-zero/rest/internal/header" ) var ( errorHandler func(context.Context, error) (int, any) errorLock sync.RWMutex okHandler func(context.Context, any) any okLock sync.RWMutex ) // Error writes err into w. func Error(w http.ResponseWriter, err error, fns ...func(w http.ResponseWriter, err error)) { doHandleError(w, err, buildErrorHandler(context.Background()), WriteJson, fns...) } // ErrorCtx writes err into w. func ErrorCtx(ctx context.Context, w http.ResponseWriter, err error, fns ...func(w http.ResponseWriter, err error)) { writeJson := func(w http.ResponseWriter, code int, v any) { WriteJsonCtx(ctx, w, code, v) } doHandleError(w, err, buildErrorHandler(ctx), writeJson, fns...) } // Ok writes HTTP 200 OK into w. func Ok(w http.ResponseWriter) { w.WriteHeader(http.StatusOK) } // OkJson writes v into w with 200 OK. func OkJson(w http.ResponseWriter, v any) { okLock.RLock() handler := okHandler okLock.RUnlock() if handler != nil { v = handler(context.Background(), v) } WriteJson(w, http.StatusOK, v) } // OkJsonCtx writes v into w with 200 OK. func OkJsonCtx(ctx context.Context, w http.ResponseWriter, v any) { okLock.RLock() handlerCtx := okHandler okLock.RUnlock() if handlerCtx != nil { v = handlerCtx(ctx, v) } WriteJsonCtx(ctx, w, http.StatusOK, v) } // SetErrorHandler sets the error handler, which is called on calling Error. // Notice: SetErrorHandler and SetErrorHandlerCtx set the same error handler. // Keeping both SetErrorHandler and SetErrorHandlerCtx is for backward compatibility. func SetErrorHandler(handler func(error) (int, any)) { errorLock.Lock() defer errorLock.Unlock() errorHandler = func(_ context.Context, err error) (int, any) { return handler(err) } } // SetErrorHandlerCtx sets the error handler, which is called on calling Error. // Notice: SetErrorHandler and SetErrorHandlerCtx set the same error handler. // Keeping both SetErrorHandler and SetErrorHandlerCtx is for backward compatibility. func SetErrorHandlerCtx(handlerCtx func(context.Context, error) (int, any)) { errorLock.Lock() defer errorLock.Unlock() errorHandler = handlerCtx } // SetOkHandler sets the response handler, which is called on calling OkJson and OkJsonCtx. func SetOkHandler(handler func(context.Context, any) any) { okLock.Lock() defer okLock.Unlock() okHandler = handler } // Stream writes data into w with streaming mode. // The ctx is used to control the streaming loop, typically use r.Context(). // The fn is called repeatedly until it returns false. func Stream(ctx context.Context, w http.ResponseWriter, fn func(w io.Writer) bool) { for { select { case <-ctx.Done(): return default: hasMore := fn(w) if flusher, ok := w.(http.Flusher); ok { flusher.Flush() } if !hasMore { return } } } } // WriteJson writes v as json string into w with code. func WriteJson(w http.ResponseWriter, code int, v any) { if err := doWriteJson(w, code, v); err != nil { logx.Error(err) } } // WriteJsonCtx writes v as json string into w with code. func WriteJsonCtx(ctx context.Context, w http.ResponseWriter, code int, v any) { if err := doWriteJson(w, code, v); err != nil { logc.Error(ctx, err) } } func buildErrorHandler(ctx context.Context) func(error) (int, any) { errorLock.RLock() handlerCtx := errorHandler errorLock.RUnlock() var handler func(error) (int, any) if handlerCtx != nil { handler = func(err error) (int, any) { return handlerCtx(ctx, err) } } return handler } func doHandleError(w http.ResponseWriter, err error, handler func(error) (int, any), writeJson func(w http.ResponseWriter, code int, v any), fns ...func(w http.ResponseWriter, err error)) { if handler == nil { if len(fns) > 0 { for _, fn := range fns { fn(w, err) } } else if errcode.IsGrpcError(err) { // don't unwrap error and get status.Message(), // it hides the rpc error headers. http.Error(w, err.Error(), errcode.CodeFromGrpcError(err)) } else { http.Error(w, err.Error(), http.StatusBadRequest) } return } code, body := handler(err) if body == nil { w.WriteHeader(code) return } switch v := body.(type) { case error: http.Error(w, v.Error(), code) default: writeJson(w, code, body) } } func doWriteJson(w http.ResponseWriter, code int, v any) error { bs, err := jsonx.Marshal(v) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return fmt.Errorf("marshal json failed, error: %w", err) } w.Header().Set(ContentType, header.ContentTypeJson) w.WriteHeader(code) if n, err := w.Write(bs); err != nil { // http.ErrHandlerTimeout has been handled by http.TimeoutHandler, // so it's ignored here. if !errors.Is(err, http.ErrHandlerTimeout) { return fmt.Errorf("write response failed, error: %w", err) } } else if n < len(bs) { return fmt.Errorf("actual bytes: %d, written bytes: %d", len(bs), n) } return nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpx/vars.go
rest/httpx/vars.go
package httpx import "github.com/zeromicro/go-zero/rest/internal/header" const ( // ContentEncoding means Content-Encoding. ContentEncoding = "Content-Encoding" // ContentSecurity means X-Content-Security. ContentSecurity = "X-Content-Security" // ContentType means Content-Type. ContentType = header.ContentType // JsonContentType means application/json. JsonContentType = header.ContentTypeJson // KeyField means key. KeyField = "key" // SecretField means secret. SecretField = "secret" // TypeField means type. TypeField = "type" // CryptionType means cryption. CryptionType = 1 ) const ( // CodeSignaturePass means signature verification passed. CodeSignaturePass = iota // CodeSignatureInvalidHeader means invalid header in signature. CodeSignatureInvalidHeader // CodeSignatureWrongTime means wrong timestamp in signature. CodeSignatureWrongTime // CodeSignatureInvalidToken means invalid token in signature. CodeSignatureInvalidToken )
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpx/responses_test.go
rest/httpx/responses_test.go
package httpx import ( "bytes" "context" "errors" "fmt" "io" "net/http" "net/http/httptest" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/logx" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) type message struct { Name string `json:"name"` } func init() { logx.Disable() } func TestError(t *testing.T) { const ( body = "foo" wrappedBody = `"foo"` ) tests := []struct { name string input string errorHandler func(error) (int, any) expectHasBody bool expectBody string expectCode int }{ { name: "default error handler", input: body, expectHasBody: true, expectBody: body, expectCode: http.StatusBadRequest, }, { name: "customized error handler return string", input: body, errorHandler: func(err error) (int, any) { return http.StatusForbidden, err.Error() }, expectHasBody: true, expectBody: wrappedBody, expectCode: http.StatusForbidden, }, { name: "customized error handler return error", input: body, errorHandler: func(err error) (int, any) { return http.StatusForbidden, err }, expectHasBody: true, expectBody: body, expectCode: http.StatusForbidden, }, { name: "customized error handler return nil", input: body, errorHandler: func(err error) (int, any) { return http.StatusForbidden, nil }, expectHasBody: false, expectBody: "", expectCode: http.StatusForbidden, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { w := tracedResponseWriter{ headers: make(map[string][]string), } if test.errorHandler != nil { errorLock.RLock() prev := errorHandler errorLock.RUnlock() SetErrorHandler(test.errorHandler) defer func() { errorLock.Lock() errorHandler = prev errorLock.Unlock() }() } Error(&w, errors.New(test.input)) assert.Equal(t, test.expectCode, w.code) assert.Equal(t, test.expectHasBody, w.hasBody) assert.Equal(t, test.expectBody, strings.TrimSpace(w.builder.String())) }) } } func TestErrorWithGrpcError(t *testing.T) { w := tracedResponseWriter{ headers: make(map[string][]string), } Error(&w, status.Error(codes.Unavailable, "foo")) assert.Equal(t, http.StatusServiceUnavailable, w.code) assert.True(t, w.hasBody) assert.True(t, strings.Contains(w.builder.String(), "foo")) } func TestErrorWithHandler(t *testing.T) { w := tracedResponseWriter{ headers: make(map[string][]string), } Error(&w, errors.New("foo"), func(w http.ResponseWriter, err error) { http.Error(w, err.Error(), 499) }) assert.Equal(t, 499, w.code) assert.True(t, w.hasBody) assert.Equal(t, "foo", strings.TrimSpace(w.builder.String())) } func TestOk(t *testing.T) { w := tracedResponseWriter{ headers: make(map[string][]string), } Ok(&w) assert.Equal(t, http.StatusOK, w.code) } func TestOkJson(t *testing.T) { t.Run("no handler", func(t *testing.T) { w := tracedResponseWriter{ headers: make(map[string][]string), } msg := message{Name: "anyone"} OkJson(&w, msg) assert.Equal(t, http.StatusOK, w.code) assert.Equal(t, "{\"name\":\"anyone\"}", w.builder.String()) }) t.Run("with handler", func(t *testing.T) { okLock.RLock() prev := okHandler okLock.RUnlock() t.Cleanup(func() { okLock.Lock() okHandler = prev okLock.Unlock() }) SetOkHandler(func(_ context.Context, v interface{}) any { return fmt.Sprintf("hello %s", v.(message).Name) }) w := tracedResponseWriter{ headers: make(map[string][]string), } msg := message{Name: "anyone"} OkJson(&w, msg) assert.Equal(t, http.StatusOK, w.code) assert.Equal(t, `"hello anyone"`, w.builder.String()) }) } func TestOkJsonCtx(t *testing.T) { t.Run("no handler", func(t *testing.T) { w := tracedResponseWriter{ headers: make(map[string][]string), } msg := message{Name: "anyone"} OkJsonCtx(context.Background(), &w, msg) assert.Equal(t, http.StatusOK, w.code) assert.Equal(t, "{\"name\":\"anyone\"}", w.builder.String()) }) t.Run("with handler", func(t *testing.T) { okLock.RLock() prev := okHandler okLock.RUnlock() t.Cleanup(func() { okLock.Lock() okHandler = prev okLock.Unlock() }) SetOkHandler(func(_ context.Context, v interface{}) any { return fmt.Sprintf("hello %s", v.(message).Name) }) w := tracedResponseWriter{ headers: make(map[string][]string), } msg := message{Name: "anyone"} OkJsonCtx(context.Background(), &w, msg) assert.Equal(t, http.StatusOK, w.code) assert.Equal(t, `"hello anyone"`, w.builder.String()) }) } func TestWriteJsonTimeout(t *testing.T) { // only log it and ignore w := tracedResponseWriter{ headers: make(map[string][]string), err: http.ErrHandlerTimeout, } msg := message{Name: "anyone"} WriteJson(&w, http.StatusOK, msg) assert.Equal(t, http.StatusOK, w.code) } func TestWriteJsonError(t *testing.T) { // only log it and ignore w := tracedResponseWriter{ headers: make(map[string][]string), err: errors.New("foo"), } msg := message{Name: "anyone"} WriteJson(&w, http.StatusOK, msg) assert.Equal(t, http.StatusOK, w.code) } func TestWriteJsonLessWritten(t *testing.T) { w := tracedResponseWriter{ headers: make(map[string][]string), lessWritten: true, } msg := message{Name: "anyone"} WriteJson(&w, http.StatusOK, msg) assert.Equal(t, http.StatusOK, w.code) } func TestWriteJsonMarshalFailed(t *testing.T) { w := tracedResponseWriter{ headers: make(map[string][]string), } WriteJson(&w, http.StatusOK, map[string]any{ "Data": complex(0, 0), }) assert.Equal(t, http.StatusInternalServerError, w.code) } func TestStream(t *testing.T) { t.Run("regular case", func(t *testing.T) { channel := make(chan string) go func() { defer close(channel) for index := 0; index < 5; index++ { channel <- fmt.Sprintf("%d", index) } }() w := httptest.NewRecorder() Stream(context.Background(), w, func(w io.Writer) bool { output, ok := <-channel if !ok { return false } outputBytes := bytes.NewBufferString(output) _, err := w.Write(append(outputBytes.Bytes(), []byte("\n")...)) return err == nil }) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "0\n1\n2\n3\n4\n", w.Body.String()) }) t.Run("context done", func(t *testing.T) { channel := make(chan string) go func() { defer close(channel) for index := 0; index < 5; index++ { channel <- fmt.Sprintf("num: %d", index) } }() w := httptest.NewRecorder() ctx, cancel := context.WithCancel(context.Background()) cancel() Stream(ctx, w, func(w io.Writer) bool { output, ok := <-channel if !ok { return false } outputBytes := bytes.NewBufferString(output) _, err := w.Write(append(outputBytes.Bytes(), []byte("\n")...)) return err == nil }) assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "", w.Body.String()) }) } type tracedResponseWriter struct { headers map[string][]string builder strings.Builder hasBody bool code int lessWritten bool wroteHeader bool err error } func (w *tracedResponseWriter) Header() http.Header { return w.headers } func (w *tracedResponseWriter) Write(bytes []byte) (n int, err error) { if w.err != nil { return 0, w.err } n, err = w.builder.Write(bytes) if w.lessWritten { n-- } w.hasBody = true return } func (w *tracedResponseWriter) WriteHeader(code int) { if w.wroteHeader { return } w.wroteHeader = true w.code = code } func TestErrorCtx(t *testing.T) { const ( body = "foo" wrappedBody = `"foo"` ) tests := []struct { name string input string errorHandlerCtx func(context.Context, error) (int, any) expectHasBody bool expectBody string expectCode int }{ { name: "default error handler", input: body, expectHasBody: true, expectBody: body, expectCode: http.StatusBadRequest, }, { name: "customized error handler return string", input: body, errorHandlerCtx: func(ctx context.Context, err error) (int, any) { return http.StatusForbidden, err.Error() }, expectHasBody: true, expectBody: wrappedBody, expectCode: http.StatusForbidden, }, { name: "customized error handler return error", input: body, errorHandlerCtx: func(ctx context.Context, err error) (int, any) { return http.StatusForbidden, err }, expectHasBody: true, expectBody: body, expectCode: http.StatusForbidden, }, { name: "customized error handler return nil", input: body, errorHandlerCtx: func(context.Context, error) (int, any) { return http.StatusForbidden, nil }, expectHasBody: false, expectBody: "", expectCode: http.StatusForbidden, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { w := tracedResponseWriter{ headers: make(map[string][]string), } if test.errorHandlerCtx != nil { errorLock.RLock() prev := errorHandler errorLock.RUnlock() SetErrorHandlerCtx(test.errorHandlerCtx) defer func() { errorLock.Lock() test.errorHandlerCtx = prev errorLock.Unlock() }() } ErrorCtx(context.Background(), &w, errors.New(test.input)) assert.Equal(t, test.expectCode, w.code) assert.Equal(t, test.expectHasBody, w.hasBody) assert.Equal(t, test.expectBody, strings.TrimSpace(w.builder.String())) }) } // The current handler is a global event,Set default values to avoid impacting subsequent unit tests SetErrorHandlerCtx(nil) } func TestErrorWithGrpcErrorCtx(t *testing.T) { w := tracedResponseWriter{ headers: make(map[string][]string), } ErrorCtx(context.Background(), &w, status.Error(codes.Unavailable, "foo")) assert.Equal(t, http.StatusServiceUnavailable, w.code) assert.True(t, w.hasBody) assert.True(t, strings.Contains(w.builder.String(), "foo")) } func TestErrorWithHandlerCtx(t *testing.T) { w := tracedResponseWriter{ headers: make(map[string][]string), } ErrorCtx(context.Background(), &w, errors.New("foo"), func(w http.ResponseWriter, err error) { http.Error(w, err.Error(), 499) }) assert.Equal(t, 499, w.code) assert.True(t, w.hasBody) assert.Equal(t, "foo", strings.TrimSpace(w.builder.String())) } func TestWriteJsonCtxMarshalFailed(t *testing.T) { w := tracedResponseWriter{ headers: make(map[string][]string), } WriteJsonCtx(context.Background(), &w, http.StatusOK, map[string]any{ "Data": complex(0, 0), }) assert.Equal(t, http.StatusInternalServerError, w.code) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/httpx/util_test.go
rest/httpx/util_test.go
package httpx import ( "fmt" "net/http" "net/url" "strings" "testing" "github.com/stretchr/testify/assert" ) func TestGetRemoteAddr(t *testing.T) { host := "8.8.8.8" r, err := http.NewRequest(http.MethodGet, "/", strings.NewReader("")) assert.Nil(t, err) r.Header.Set(xForwardedFor, host) assert.Equal(t, host, GetRemoteAddr(r)) } func TestGetRemoteAddrNoHeader(t *testing.T) { r, err := http.NewRequest(http.MethodGet, "/", strings.NewReader("")) assert.Nil(t, err) assert.True(t, len(GetRemoteAddr(r)) == 0) } func TestGetFormValues_TooManyValues(t *testing.T) { form := url.Values{} // Add more values than the limit for i := 0; i < maxFormParamCount+10; i++ { form.Add("param", fmt.Sprintf("value%d", i)) } // Create a new request with the form data req, err := http.NewRequest("POST", "/test", strings.NewReader(form.Encode())) assert.NoError(t, err) // Set the content type for form data req.Header.Set(ContentType, "application/x-www-form-urlencoded") _, err = GetFormValues(req) assert.Error(t, err) assert.Contains(t, err.Error(), "too many form values") }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/pathvar/params.go
rest/pathvar/params.go
package pathvar import ( "context" "net/http" ) var pathVars = contextKey("pathVars") // Vars parses path variables and returns a map. func Vars(r *http.Request) map[string]string { vars, ok := r.Context().Value(pathVars).(map[string]string) if ok { return vars } return nil } // WithVars writes params into given r and returns a new http.Request. func WithVars(r *http.Request, params map[string]string) *http.Request { return r.WithContext(context.WithValue(r.Context(), pathVars, params)) } type contextKey string func (c contextKey) String() string { return "rest/pathvar/context key: " + string(c) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/pathvar/params_test.go
rest/pathvar/params_test.go
package pathvar import ( "net/http" "strings" "testing" "github.com/stretchr/testify/assert" ) func TestVars(t *testing.T) { expect := map[string]string{ "a": "1", "b": "2", } r, err := http.NewRequest(http.MethodGet, "/", nil) assert.Nil(t, err) r = WithVars(r, expect) assert.EqualValues(t, expect, Vars(r)) } func TestVarsNil(t *testing.T) { r, err := http.NewRequest(http.MethodGet, "/", nil) assert.Nil(t, err) assert.Nil(t, Vars(r)) } func TestContextKey(t *testing.T) { ck := contextKey("hello") assert.True(t, strings.Contains(ck.String(), "hello")) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/internal/starter.go
rest/internal/starter.go
package internal import ( "context" "errors" "fmt" "net/http" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/proc" "github.com/zeromicro/go-zero/internal/health" ) const probeNamePrefix = "rest" // StartOption defines the method to customize http.Server. type StartOption func(svr *http.Server) // StartHttp starts a http server. func StartHttp(host string, port int, handler http.Handler, opts ...StartOption) error { return start(host, port, handler, func(svr *http.Server) error { return svr.ListenAndServe() }, opts...) } // StartHttps starts a https server. func StartHttps(host string, port int, certFile, keyFile string, handler http.Handler, opts ...StartOption) error { return start(host, port, handler, func(svr *http.Server) error { // certFile and keyFile are set in buildHttpsServer return svr.ListenAndServeTLS(certFile, keyFile) }, opts...) } func start(host string, port int, handler http.Handler, run func(svr *http.Server) error, opts ...StartOption) (err error) { server := &http.Server{ Addr: fmt.Sprintf("%s:%d", host, port), Handler: handler, } for _, opt := range opts { opt(server) } healthManager := health.NewHealthManager(fmt.Sprintf("%s-%s:%d", probeNamePrefix, host, port)) waitForCalled := proc.AddShutdownListener(func() { healthManager.MarkNotReady() if e := server.Shutdown(context.Background()); e != nil { logx.Error(e) } }) defer func() { if errors.Is(err, http.ErrServerClosed) { waitForCalled() } }() healthManager.MarkReady() health.AddProbe(healthManager) return run(server) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/internal/log_test.go
rest/internal/log_test.go
package internal import ( "context" "net/http" "net/http/httptest" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/logx/logtest" ) func TestInfo(t *testing.T) { collector := new(LogCollector) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) req = req.WithContext(WithLogCollector(req.Context(), collector)) Info(req, "first") Infof(req, "second %s", "third") val := collector.Flush() assert.True(t, strings.Contains(val, "first")) assert.True(t, strings.Contains(val, "second")) assert.True(t, strings.Contains(val, "third")) assert.True(t, strings.Contains(val, "\n")) } func TestError(t *testing.T) { c := logtest.NewCollector(t) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) Error(req, "first") Errorf(req, "second %s", "third") val := c.String() assert.True(t, strings.Contains(val, "first")) assert.True(t, strings.Contains(val, "second")) assert.True(t, strings.Contains(val, "third")) } func TestLogCollectorContext(t *testing.T) { ctx := context.Background() assert.Nil(t, LogCollectorFromContext(ctx)) collector := new(LogCollector) ctx = WithLogCollector(ctx, collector) assert.Equal(t, collector, LogCollectorFromContext(ctx)) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/internal/starter_test.go
rest/internal/starter_test.go
package internal import ( "net/http" "net/http/httptest" "strconv" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/proc" ) func TestStartHttp(t *testing.T) { svr := httptest.NewUnstartedServer(http.NotFoundHandler()) fields := strings.Split(svr.Listener.Addr().String(), ":") port, err := strconv.Atoi(fields[1]) assert.Nil(t, err) err = StartHttp(fields[0], port, http.NotFoundHandler(), func(svr *http.Server) { svr.IdleTimeout = 0 }) assert.NotNil(t, err) proc.WrapUp() } func TestStartHttps(t *testing.T) { svr := httptest.NewTLSServer(http.NotFoundHandler()) fields := strings.Split(svr.Listener.Addr().String(), ":") port, err := strconv.Atoi(fields[1]) assert.Nil(t, err) err = StartHttps(fields[0], port, "", "", http.NotFoundHandler(), func(svr *http.Server) { svr.IdleTimeout = 0 }) assert.NotNil(t, err) proc.WrapUp() }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/internal/log.go
rest/internal/log.go
package internal import ( "bytes" "context" "fmt" "net/http" "sync" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/rest/httpx" ) // logContextKey is a context key. var logContextKey = contextKey("request_logs") type ( // LogCollector is used to collect logs. LogCollector struct { Messages []string lock sync.Mutex } contextKey string ) // WithLogCollector returns a new context with LogCollector. func WithLogCollector(ctx context.Context, lc *LogCollector) context.Context { return context.WithValue(ctx, logContextKey, lc) } // LogCollectorFromContext returns LogCollector from ctx. func LogCollectorFromContext(ctx context.Context) *LogCollector { val := ctx.Value(logContextKey) if val == nil { return nil } return val.(*LogCollector) } // Append appends msg into log context. func (lc *LogCollector) Append(msg string) { lc.lock.Lock() lc.Messages = append(lc.Messages, msg) lc.lock.Unlock() } // Flush flushes collected logs. func (lc *LogCollector) Flush() string { var buffer bytes.Buffer start := true for _, message := range lc.takeAll() { if start { start = false } else { buffer.WriteByte('\n') } buffer.WriteString(message) } return buffer.String() } func (lc *LogCollector) takeAll() []string { lc.lock.Lock() messages := lc.Messages lc.Messages = nil lc.lock.Unlock() return messages } // Error logs the given v along with r in error log. func Error(r *http.Request, v ...any) { logx.WithContext(r.Context()).Error(format(r, v...)) } // Errorf logs the given v with format along with r in error log. func Errorf(r *http.Request, format string, v ...any) { logx.WithContext(r.Context()).Error(formatf(r, format, v...)) } // Info logs the given v along with r in access log. func Info(r *http.Request, v ...any) { appendLog(r, format(r, v...)) } // Infof logs the given v with format along with r in access log. func Infof(r *http.Request, format string, v ...any) { appendLog(r, formatf(r, format, v...)) } func appendLog(r *http.Request, message string) { logs := LogCollectorFromContext(r.Context()) if logs != nil { logs.Append(message) } } func format(r *http.Request, v ...any) string { return formatWithReq(r, fmt.Sprint(v...)) } func formatf(r *http.Request, format string, v ...any) string { return formatWithReq(r, fmt.Sprintf(format, v...)) } func formatWithReq(r *http.Request, v string) string { return fmt.Sprintf("(%s - %s) %s", r.RequestURI, httpx.GetRemoteAddr(r), v) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/internal/encoding/parser.go
rest/internal/encoding/parser.go
package encoding import ( "net/http" "net/textproto" "github.com/zeromicro/go-zero/core/mapping" ) const headerKey = "header" var headerUnmarshaler = mapping.NewUnmarshaler(headerKey, mapping.WithStringValues(), mapping.WithCanonicalKeyFunc(textproto.CanonicalMIMEHeaderKey)) // ParseHeaders parses the headers request. func ParseHeaders(header http.Header, v any) error { m := map[string]any{} for k, v := range header { if len(v) == 1 { m[k] = v[0] } else { m[k] = v } } return headerUnmarshaler.Unmarshal(m, v) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/internal/encoding/parser_test.go
rest/internal/encoding/parser_test.go
package encoding import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestParseHeaders(t *testing.T) { var val struct { Foo string `header:"foo"` Baz int `header:"baz"` Qux bool `header:"qux,default=true"` } r := httptest.NewRequest(http.MethodGet, "/any", http.NoBody) r.Header.Set("foo", "bar") r.Header.Set("baz", "1") assert.Nil(t, ParseHeaders(r.Header, &val)) assert.Equal(t, "bar", val.Foo) assert.Equal(t, 1, val.Baz) assert.True(t, val.Qux) } func TestParseHeadersMulti(t *testing.T) { var val struct { Foo []string `header:"foo"` Baz int `header:"baz"` Qux bool `header:"qux,default=true"` } r := httptest.NewRequest(http.MethodGet, "/any", http.NoBody) r.Header.Set("foo", "bar") r.Header.Add("foo", "bar1") r.Header.Set("baz", "1") assert.Nil(t, ParseHeaders(r.Header, &val)) assert.Equal(t, []string{"bar", "bar1"}, val.Foo) assert.Equal(t, 1, val.Baz) assert.True(t, val.Qux) } func TestParseHeadersArrayInt(t *testing.T) { var val struct { Foo []int `header:"foo"` } r := httptest.NewRequest(http.MethodGet, "/any", http.NoBody) r.Header.Set("foo", "1") r.Header.Add("foo", "2") assert.Nil(t, ParseHeaders(r.Header, &val)) assert.Equal(t, []int{1, 2}, val.Foo) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/internal/errcode/grpc_test.go
rest/internal/errcode/grpc_test.go
package errcode import ( "errors" "net/http" "testing" "github.com/stretchr/testify/assert" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) func TestCodeFromGrpcError(t *testing.T) { tests := []struct { name string code codes.Code want int }{ { name: "OK", code: codes.OK, want: http.StatusOK, }, { name: "Invalid argument", code: codes.InvalidArgument, want: http.StatusBadRequest, }, { name: "Failed precondition", code: codes.FailedPrecondition, want: http.StatusBadRequest, }, { name: "Out of range", code: codes.OutOfRange, want: http.StatusBadRequest, }, { name: "Unauthorized", code: codes.Unauthenticated, want: http.StatusUnauthorized, }, { name: "Permission denied", code: codes.PermissionDenied, want: http.StatusForbidden, }, { name: "Not found", code: codes.NotFound, want: http.StatusNotFound, }, { name: "Canceled", code: codes.Canceled, want: http.StatusRequestTimeout, }, { name: "Already exists", code: codes.AlreadyExists, want: http.StatusConflict, }, { name: "Aborted", code: codes.Aborted, want: http.StatusConflict, }, { name: "Resource exhausted", code: codes.ResourceExhausted, want: http.StatusTooManyRequests, }, { name: "Internal", code: codes.Internal, want: http.StatusInternalServerError, }, { name: "Data loss", code: codes.DataLoss, want: http.StatusInternalServerError, }, { name: "Unknown", code: codes.Unknown, want: http.StatusInternalServerError, }, { name: "Unimplemented", code: codes.Unimplemented, want: http.StatusNotImplemented, }, { name: "Unavailable", code: codes.Unavailable, want: http.StatusServiceUnavailable, }, { name: "Deadline exceeded", code: codes.DeadlineExceeded, want: http.StatusGatewayTimeout, }, { name: "Beyond defined error", code: codes.Code(^uint32(0)), want: http.StatusInternalServerError, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { assert.Equal(t, test.want, CodeFromGrpcError(status.Error(test.code, "foo"))) }) } } func TestIsGrpcError(t *testing.T) { assert.True(t, IsGrpcError(status.Error(codes.Unknown, "foo"))) assert.False(t, IsGrpcError(errors.New("foo"))) assert.False(t, IsGrpcError(nil)) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/internal/errcode/grpc.go
rest/internal/errcode/grpc.go
package errcode import ( "net/http" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) // CodeFromGrpcError converts the gRPC error to an HTTP status code. // See: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto func CodeFromGrpcError(err error) int { code := status.Code(err) switch code { case codes.OK: return http.StatusOK case codes.InvalidArgument, codes.FailedPrecondition, codes.OutOfRange: return http.StatusBadRequest case codes.Unauthenticated: return http.StatusUnauthorized case codes.PermissionDenied: return http.StatusForbidden case codes.NotFound: return http.StatusNotFound case codes.Canceled: return http.StatusRequestTimeout case codes.AlreadyExists, codes.Aborted: return http.StatusConflict case codes.ResourceExhausted: return http.StatusTooManyRequests case codes.Internal, codes.DataLoss, codes.Unknown: return http.StatusInternalServerError case codes.Unimplemented: return http.StatusNotImplemented case codes.Unavailable: return http.StatusServiceUnavailable case codes.DeadlineExceeded: return http.StatusGatewayTimeout } return http.StatusInternalServerError } // IsGrpcError checks if the error is a gRPC error. func IsGrpcError(err error) bool { if err == nil { return false } _, ok := err.(interface { GRPCStatus() *status.Status }) return ok }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/internal/cors/handlers_test.go
rest/internal/cors/handlers_test.go
package cors import ( "net/http" "net/http/httptest" "strings" "testing" "github.com/stretchr/testify/assert" ) func TestAddAllowHeaders(t *testing.T) { tests := []struct { name string initial string headers []string expected string }{ { name: "single header", initial: "", headers: []string{"Content-Type"}, expected: "Content-Type", }, { name: "multiple headers", initial: "", headers: []string{"Content-Type", "Authorization", "X-Requested-With"}, expected: "Content-Type, Authorization, X-Requested-With", }, { name: "add to existing headers", initial: "Origin, Accept", headers: []string{"Content-Type"}, expected: "Origin, Accept, Content-Type", }, { name: "no headers", initial: "", headers: []string{}, expected: "", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { header := http.Header{} headers := make(map[string]struct{}) if tt.initial != "" { header.Set(allowHeaders, tt.initial) vals := strings.Split(tt.initial, ", ") for _, v := range vals { headers[v] = struct{}{} } } for _, h := range tt.headers { headers[h] = struct{}{} } AddAllowHeaders(header, tt.headers...) var actual []string vals := header.Values(allowHeaders) for _, v := range vals { bunch := strings.Split(v, ", ") for _, b := range bunch { if len(b) > 0 { actual = append(actual, b) } } } var expect []string for k := range headers { expect = append(expect, k) } assert.ElementsMatch(t, expect, actual) }) } } func TestCorsHandlerWithOrigins(t *testing.T) { tests := []struct { name string origins []string reqOrigin string expect string }{ { name: "allow all origins", expect: allOrigins, }, { name: "allow one origin", origins: []string{"http://local"}, reqOrigin: "http://local", expect: "http://local", }, { name: "allow many origins", origins: []string{"http://local", "http://remote"}, 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", expect: "*", }, { name: "allow many origins with all mark", origins: []string{"http://local", "http://remote", "*"}, reqOrigin: "http://another", expect: "http://another", }, { name: "not allow origin", origins: []string{"http://local", "http://remote"}, reqOrigin: "http://another", }, { name: "not safe origin", origins: []string{"safe.com"}, reqOrigin: "not-safe.com", }, } methods := []string{ http.MethodOptions, http.MethodGet, http.MethodPost, } for _, test := range tests { for _, method := range methods { test := test t.Run(test.name+"-handler", func(t *testing.T) { r := httptest.NewRequest(method, "http://localhost", http.NoBody) r.Header.Set(originHeader, test.reqOrigin) w := httptest.NewRecorder() handler := NotAllowedHandler(nil, test.origins...) handler.ServeHTTP(w, r) if method == http.MethodOptions { assert.Equal(t, http.StatusNoContent, w.Result().StatusCode) } else { assert.Equal(t, http.StatusNotFound, w.Result().StatusCode) } assert.Equal(t, test.expect, w.Header().Get(allowOrigin)) }) t.Run(test.name+"-handler-custom", func(t *testing.T) { r := httptest.NewRequest(method, "http://localhost", http.NoBody) r.Header.Set(originHeader, test.reqOrigin) w := httptest.NewRecorder() handler := NotAllowedHandler(func(w http.ResponseWriter) { w.Header().Set("foo", "bar") }, test.origins...) handler.ServeHTTP(w, r) if method == http.MethodOptions { assert.Equal(t, http.StatusNoContent, w.Result().StatusCode) } else { assert.Equal(t, http.StatusNotFound, w.Result().StatusCode) } assert.Equal(t, test.expect, w.Header().Get(allowOrigin)) assert.Equal(t, "bar", w.Header().Get("foo")) }) } } for _, test := range tests { for _, method := range methods { test := test t.Run(test.name+"-middleware", func(t *testing.T) { r := httptest.NewRequest(method, "http://localhost", http.NoBody) r.Header.Set(originHeader, test.reqOrigin) w := httptest.NewRecorder() handler := Middleware(nil, test.origins...)(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }) handler.ServeHTTP(w, r) if method == http.MethodOptions { assert.Equal(t, http.StatusNoContent, w.Result().StatusCode) } else { assert.Equal(t, http.StatusOK, w.Result().StatusCode) } assert.Equal(t, test.expect, w.Header().Get(allowOrigin)) }) t.Run(test.name+"-middleware-custom", func(t *testing.T) { r := httptest.NewRequest(method, "http://localhost", http.NoBody) r.Header.Set(originHeader, test.reqOrigin) w := httptest.NewRecorder() handler := Middleware(func(header http.Header) { header.Set("foo", "bar") }, test.origins...)(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }) handler.ServeHTTP(w, r) if method == http.MethodOptions { assert.Equal(t, http.StatusNoContent, w.Result().StatusCode) } else { assert.Equal(t, http.StatusOK, w.Result().StatusCode) } assert.Equal(t, test.expect, w.Header().Get(allowOrigin)) assert.Equal(t, "bar", w.Header().Get("foo")) }) } } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/internal/cors/handlers.go
rest/internal/cors/handlers.go
package cors import ( "net/http" "strings" "github.com/zeromicro/go-zero/rest/internal/response" ) const ( allowOrigin = "Access-Control-Allow-Origin" allOrigins = "*" allowMethods = "Access-Control-Allow-Methods" allowHeaders = "Access-Control-Allow-Headers" allowCredentials = "Access-Control-Allow-Credentials" exposeHeaders = "Access-Control-Expose-Headers" requestMethod = "Access-Control-Request-Method" requestHeaders = "Access-Control-Request-Headers" allowHeadersVal = "Content-Type, Origin, X-CSRF-Token, Authorization, AccessToken, Token, Range" exposeHeadersVal = "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers" methods = "GET, HEAD, POST, PATCH, PUT, DELETE" allowTrue = "true" maxAgeHeader = "Access-Control-Max-Age" maxAgeHeaderVal = "86400" varyHeader = "Vary" originHeader = "Origin" ) // AddAllowHeaders sets the allowed headers. func AddAllowHeaders(header http.Header, headers ...string) { header.Add(allowHeaders, strings.Join(headers, ", ")) } // NotAllowedHandler handles cross domain not allowed requests. // At most one origin can be specified, other origins are ignored if given, default to be *. func NotAllowedHandler(fn func(w http.ResponseWriter), origins ...string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gw := response.NewHeaderOnceResponseWriter(w) checkAndSetHeaders(gw, r, origins) if fn != nil { fn(gw) } if r.Method == http.MethodOptions { gw.WriteHeader(http.StatusNoContent) } else { gw.WriteHeader(http.StatusNotFound) } }) } // Middleware returns a middleware that adds CORS headers to the response. func Middleware(fn func(w http.Header), origins ...string) func(http.HandlerFunc) http.HandlerFunc { return func(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { checkAndSetHeaders(w, r, origins) if fn != nil { fn(w.Header()) } if r.Method == http.MethodOptions { w.WriteHeader(http.StatusNoContent) } else { next(w, r) } } } } func checkAndSetHeaders(w http.ResponseWriter, r *http.Request, origins []string) { setVaryHeaders(w, r) if len(origins) == 0 { setHeader(w, allOrigins) return } origin := r.Header.Get(originHeader) if isOriginAllowed(origins, origin) { setHeader(w, origin) } } func isOriginAllowed(allows []string, origin string) bool { origin = strings.ToLower(origin) for _, allow := range allows { if allow == allOrigins { return true } allow = strings.ToLower(allow) if origin == allow { return true } if strings.HasSuffix(origin, "."+allow) { return true } } return false } func setHeader(w http.ResponseWriter, origin string) { header := w.Header() header.Set(allowOrigin, origin) header.Set(allowMethods, methods) header.Set(allowHeaders, allowHeadersVal) header.Set(exposeHeaders, exposeHeadersVal) if origin != allOrigins { header.Set(allowCredentials, allowTrue) } header.Set(maxAgeHeader, maxAgeHeaderVal) } func setVaryHeaders(w http.ResponseWriter, r *http.Request) { header := w.Header() header.Add(varyHeader, originHeader) if r.Method == http.MethodOptions { header.Add(varyHeader, requestMethod) header.Add(varyHeader, requestHeaders) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/internal/fileserver/filehandler.go
rest/internal/fileserver/filehandler.go
package fileserver import ( "net/http" "path" "strings" "sync" ) // Middleware returns a middleware that serves files from the given file system. func Middleware(upath string, fs http.FileSystem) func(http.HandlerFunc) http.HandlerFunc { fileServer := http.FileServer(fs) pathWithoutTrailSlash := ensureNoTrailingSlash(upath) canServe := createServeChecker(upath, fs) return func(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if canServe(r) { r.URL.Path = r.URL.Path[len(pathWithoutTrailSlash):] fileServer.ServeHTTP(w, r) } else { next(w, r) } } } } func createFileChecker(fs http.FileSystem) func(string) bool { var lock sync.RWMutex fileChecker := make(map[string]bool) return func(upath string) bool { // Emulate http.Dir.Open’s path normalization for embed.FS.Open. // http.FileServer redirects any request ending in "/index.html" // to the same path without the final "index.html". // So the path here may be empty or end with a "/". // http.Dir.Open uses this logic to clean the path, // correctly handling those two cases. // embed.FS doesn’t perform this normalization, so we apply the same logic here. upath = path.Clean("/" + upath)[1:] if len(upath) == 0 { // if the path is empty, we use "." to open the current directory upath = "." } lock.RLock() exist, ok := fileChecker[upath] lock.RUnlock() if ok { return exist } lock.Lock() defer lock.Unlock() file, err := fs.Open(upath) exist = err == nil fileChecker[upath] = exist if err != nil { return false } _ = file.Close() return true } } func createServeChecker(upath string, fs http.FileSystem) func(r *http.Request) bool { pathWithTrailSlash := ensureTrailingSlash(upath) fileChecker := createFileChecker(fs) return func(r *http.Request) bool { return r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, pathWithTrailSlash) && fileChecker(r.URL.Path[len(pathWithTrailSlash):]) } } func ensureTrailingSlash(upath string) string { if strings.HasSuffix(upath, "/") { return upath } return upath + "/" } func ensureNoTrailingSlash(upath string) string { if strings.HasSuffix(upath, "/") { return upath[:len(upath)-1] } return upath }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/internal/fileserver/filehandler_test.go
rest/internal/fileserver/filehandler_test.go
package fileserver import ( "embed" "io/fs" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestMiddleware(t *testing.T) { tests := []struct { name string path string dir string requestPath string expectedStatus int expectedContent string }{ { name: "Serve static file", path: "/static/", dir: "./testdata", requestPath: "/static/example.txt", expectedStatus: http.StatusOK, expectedContent: "1", }, { name: "Pass through non-matching path", path: "/static/", dir: "./testdata", requestPath: "/other/path", expectedStatus: http.StatusAlreadyReported, }, { name: "Directory with trailing slash", path: "/assets", dir: "testdata", requestPath: "/assets/sample.txt", expectedStatus: http.StatusOK, expectedContent: "2", }, { name: "Not exist file", path: "/assets", dir: "testdata", requestPath: "/assets/not-exist.txt", expectedStatus: http.StatusAlreadyReported, }, { name: "Not exist file in root", path: "/", dir: "testdata", requestPath: "/not-exist.txt", expectedStatus: http.StatusAlreadyReported, }, { name: "websocket request", path: "/", dir: "testdata", requestPath: "/ws", expectedStatus: http.StatusAlreadyReported, }, // http.FileServer redirects any request ending in "/index.html" // to the same path, without the final "index.html". { name: "Serve index.html", path: "/static", dir: "testdata", requestPath: "/static/index.html", expectedStatus: http.StatusMovedPermanently, }, { name: "Serve index.html with path with trailing slash", path: "/static/", dir: "testdata", requestPath: "/static/index.html", expectedStatus: http.StatusMovedPermanently, }, { name: "Serve index.html in a nested directory", path: "/static", dir: "testdata", requestPath: "/static/nested/index.html", expectedStatus: http.StatusMovedPermanently, }, { name: "Request index.html indirectly", path: "/static", dir: "testdata", requestPath: "/static/", expectedStatus: http.StatusOK, expectedContent: "hello", }, { name: "Request index.html in a nested directory indirectly", path: "/static", dir: "testdata", requestPath: "/static/nested/", expectedStatus: http.StatusOK, expectedContent: "hello", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { middleware := Middleware(tt.path, http.Dir(tt.dir)) nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusAlreadyReported) }) handlerToTest := middleware(nextHandler) for i := 0; i < 2; i++ { req := httptest.NewRequest(http.MethodGet, tt.requestPath, nil) rr := httptest.NewRecorder() handlerToTest.ServeHTTP(rr, req) assert.Equal(t, tt.expectedStatus, rr.Code) if len(tt.expectedContent) > 0 { assert.Equal(t, tt.expectedContent, rr.Body.String()) } } }) } } var ( //go:embed testdata testdataFS embed.FS ) func TestMiddleware_embedFS(t *testing.T) { tests := []struct { name string path string requestPath string expectedStatus int expectedContent string }{ { name: "Serve static file", path: "/static", requestPath: "/static/example.txt", expectedStatus: http.StatusOK, expectedContent: "1", }, { name: "Path with trailing slash", path: "/static/", requestPath: "/static/example.txt", expectedStatus: http.StatusOK, expectedContent: "1", }, { name: "Root path", path: "/", requestPath: "/example.txt", expectedStatus: http.StatusOK, expectedContent: "1", }, { name: "Pass through non-matching path", path: "/static/", requestPath: "/other/path", expectedStatus: http.StatusAlreadyReported, }, { name: "Not exist file", path: "/assets", requestPath: "/assets/not-exist.txt", expectedStatus: http.StatusAlreadyReported, }, { name: "Not exist file in root", path: "/", requestPath: "/not-exist.txt", expectedStatus: http.StatusAlreadyReported, }, { name: "websocket request", path: "/", requestPath: "/ws", expectedStatus: http.StatusAlreadyReported, }, // http.FileServer redirects any request ending in "/index.html" // to the same path, without the final "index.html". { name: "Serve index.html", path: "/static", requestPath: "/static/index.html", expectedStatus: http.StatusMovedPermanently, }, { name: "Serve index.html with path with trailing slash", path: "/static/", requestPath: "/static/index.html", expectedStatus: http.StatusMovedPermanently, }, { name: "Serve index.html in a nested directory", path: "/static", requestPath: "/static/nested/index.html", expectedStatus: http.StatusMovedPermanently, }, { name: "Request index.html indirectly", path: "/static", requestPath: "/static/", expectedStatus: http.StatusOK, expectedContent: "hello", }, { name: "Request index.html in a nested directory indirectly", path: "/static", requestPath: "/static/nested/", expectedStatus: http.StatusOK, expectedContent: "hello", }, } subFS, err := fs.Sub(testdataFS, "testdata") assert.Nil(t, err) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { middleware := Middleware(tt.path, http.FS(subFS)) nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusAlreadyReported) }) handlerToTest := middleware(nextHandler) for i := 0; i < 2; i++ { req := httptest.NewRequest(http.MethodGet, tt.requestPath, nil) rr := httptest.NewRecorder() handlerToTest.ServeHTTP(rr, req) assert.Equal(t, tt.expectedStatus, rr.Code) if len(tt.expectedContent) > 0 { assert.Equal(t, tt.expectedContent, rr.Body.String()) } } }) } } func TestEnsureTrailingSlash(t *testing.T) { tests := []struct { input string expected string }{ {"path", "path/"}, {"path/", "path/"}, } for _, tt := range tests { t.Run(tt.input, func(t *testing.T) { result := ensureTrailingSlash(tt.input) assert.Equal(t, tt.expected, result) }) } } func TestEnsureNoTrailingSlash(t *testing.T) { tests := []struct { input string expected string }{ {"path", "path"}, {"path/", "path"}, } for _, tt := range tests { t.Run(tt.input, func(t *testing.T) { result := ensureNoTrailingSlash(tt.input) assert.Equal(t, tt.expected, result) }) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/internal/security/contentsecurity_test.go
rest/internal/security/contentsecurity_test.go
package security import ( "crypto/hmac" "crypto/md5" "crypto/sha256" "encoding/base64" "fmt" "io" "log" "net/http" "os" "strconv" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/codec" "github.com/zeromicro/go-zero/core/fs" "github.com/zeromicro/go-zero/rest/httpx" ) const ( pubKey = `-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCyeDYV2ieOtNDi6tuNtAbmUjN9 pTHluAU5yiKEz8826QohcxqUKP3hybZBcm60p+rUxMAJFBJ8Dt+UJ6sEMzrf1rOF YOImVvORkXjpFU7sCJkhnLMs/kxtRzcZJG6ADUlG4GDCNcZpY/qELEvwgm2kCcHi tGC2mO8opFFFHTR0aQIDAQAB -----END PUBLIC KEY-----` priKey = `-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQCyeDYV2ieOtNDi6tuNtAbmUjN9pTHluAU5yiKEz8826QohcxqU KP3hybZBcm60p+rUxMAJFBJ8Dt+UJ6sEMzrf1rOFYOImVvORkXjpFU7sCJkhnLMs /kxtRzcZJG6ADUlG4GDCNcZpY/qELEvwgm2kCcHitGC2mO8opFFFHTR0aQIDAQAB AoGAcENv+jT9VyZkk6karLuG75DbtPiaN5+XIfAF4Ld76FWVOs9V88cJVON20xpx ixBphqexCMToj8MnXuHJEN5M9H15XXx/9IuiMm3FOw0i6o0+4V8XwHr47siT6T+r HuZEyXER/2qrm0nxyC17TXtd/+TtpfQWSbivl6xcAEo9RRECQQDj6OR6AbMQAIDn v+AhP/y7duDZimWJIuMwhigA1T2qDbtOoAEcjv3DB1dAswJ7clcnkxI9a6/0RDF9 0IEHUcX9AkEAyHdcegWiayEnbatxWcNWm1/5jFnCN+GTRRFrOhBCyFr2ZdjFV4T+ acGtG6omXWaZJy1GZz6pybOGy93NwLB93QJARKMJ0/iZDbOpHqI5hKn5mhd2Je25 IHDCTQXKHF4cAQ+7njUvwIMLx2V5kIGYuMa5mrB/KMI6rmyvHv3hLewhnQJBAMMb cPUOENMllINnzk2oEd3tXiscnSvYL4aUeoErnGP2LERZ40/YD+mMZ9g6FVboaX04 0oHf+k5mnXZD7WJyJD0CQQDJ2HyFbNaUUHK+lcifCibfzKTgmnNh9ZpePFumgJzI EfFE5H+nzsbbry2XgJbWzRNvuFTOLWn4zM+aFyy9WvbO -----END RSA PRIVATE KEY-----` body = "hello world!" ) var key = []byte("q4t7w!z%C*F-JaNdRgUjXn2r5u8x/A?D") func TestContentSecurity(t *testing.T) { tests := []struct { name string mode string extraKey string extraSecret string extraTime string err error code int }{ { name: "encrypted", mode: "1", }, { name: "unencrypted", mode: "0", }, { name: "bad content type", mode: "a", err: ErrInvalidContentType, }, { name: "bad secret", mode: "1", extraSecret: "any", err: ErrInvalidSecret, }, { name: "bad key", mode: "1", extraKey: "any", err: ErrInvalidKey, }, { name: "bad time", mode: "1", extraTime: "any", code: httpx.CodeSignatureInvalidHeader, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { t.Parallel() r, err := http.NewRequest(http.MethodPost, "http://localhost:3333/a/b?c=first&d=second", strings.NewReader(body)) assert.Nil(t, err) timestamp := time.Now().Unix() sha := sha256.New() sha.Write([]byte(body)) bodySign := fmt.Sprintf("%x", sha.Sum(nil)) contentOfSign := strings.Join([]string{ strconv.FormatInt(timestamp, 10), http.MethodPost, r.URL.Path, r.URL.RawQuery, bodySign, }, "\n") sign := hs256(key, contentOfSign) content := strings.Join([]string{ "version=v1", "type=" + test.mode, fmt.Sprintf("key=%s", base64.StdEncoding.EncodeToString(key)) + test.extraKey, "time=" + strconv.FormatInt(timestamp, 10) + test.extraTime, }, "; ") encrypter, err := codec.NewRsaEncrypter([]byte(pubKey)) if err != nil { log.Fatal(err) } output, err := encrypter.Encrypt([]byte(content)) if err != nil { log.Fatal(err) } encryptedContent := base64.StdEncoding.EncodeToString(output) r.Header.Set("X-Content-Security", strings.Join([]string{ fmt.Sprintf("key=%s", fingerprint(pubKey)), "secret=" + encryptedContent + test.extraSecret, "signature=" + sign, }, "; ")) file, err := fs.TempFilenameWithText(priKey) assert.Nil(t, err) defer os.Remove(file) dec, err := codec.NewRsaDecrypter(file) assert.Nil(t, err) header, err := ParseContentSecurity(map[string]codec.RsaDecrypter{ fingerprint(pubKey): dec, }, r) assert.Equal(t, test.err, err) if err != nil { return } encrypted := test.mode != "0" assert.Equal(t, encrypted, header.Encrypted()) assert.Equal(t, test.code, VerifySignature(r, header, time.Minute)) }) } } func fingerprint(key string) string { h := md5.New() io.WriteString(h, key) return base64.StdEncoding.EncodeToString(h.Sum(nil)) } func hs256(key []byte, body string) string { h := hmac.New(sha256.New, key) io.WriteString(h, body) return base64.StdEncoding.EncodeToString(h.Sum(nil)) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/internal/security/contentsecurity.go
rest/internal/security/contentsecurity.go
package security import ( "crypto/sha256" "encoding/base64" "errors" "fmt" "io" "net/http" "net/url" "strconv" "strings" "time" "github.com/zeromicro/go-zero/core/codec" "github.com/zeromicro/go-zero/core/iox" "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/rest/httpx" ) const ( requestUriHeader = "X-Request-Uri" signatureField = "signature" timeField = "time" ) var ( // ErrInvalidContentType is an error that indicates invalid content type. ErrInvalidContentType = errors.New("invalid content type") // ErrInvalidHeader is an error that indicates invalid X-Content-Security header. ErrInvalidHeader = errors.New("invalid X-Content-Security header") // ErrInvalidKey is an error that indicates invalid key. ErrInvalidKey = errors.New("invalid key") // ErrInvalidPublicKey is an error that indicates invalid public key. ErrInvalidPublicKey = errors.New("invalid public key") // ErrInvalidSecret is an error that indicates invalid secret. ErrInvalidSecret = errors.New("invalid secret") ) // A ContentSecurityHeader is a content security header. type ContentSecurityHeader struct { Key []byte Timestamp string ContentType int Signature string } // Encrypted checks if it's a crypted request. func (h *ContentSecurityHeader) Encrypted() bool { return h.ContentType == httpx.CryptionType } // ParseContentSecurity parses content security settings in give r. func ParseContentSecurity(decrypters map[string]codec.RsaDecrypter, r *http.Request) ( *ContentSecurityHeader, error) { contentSecurity := r.Header.Get(httpx.ContentSecurity) attrs := httpx.ParseHeader(contentSecurity) fingerprint := attrs[httpx.KeyField] secret := attrs[httpx.SecretField] signature := attrs[signatureField] if len(fingerprint) == 0 || len(secret) == 0 || len(signature) == 0 { return nil, ErrInvalidHeader } decrypter, ok := decrypters[fingerprint] if !ok { return nil, ErrInvalidPublicKey } decryptedSecret, err := decrypter.DecryptBase64(secret) if err != nil { return nil, ErrInvalidSecret } attrs = httpx.ParseHeader(string(decryptedSecret)) base64Key := attrs[httpx.KeyField] timestamp := attrs[timeField] contentType := attrs[httpx.TypeField] key, err := base64.StdEncoding.DecodeString(base64Key) if err != nil { return nil, ErrInvalidKey } cType, err := strconv.Atoi(contentType) if err != nil { return nil, ErrInvalidContentType } return &ContentSecurityHeader{ Key: key, Timestamp: timestamp, ContentType: cType, Signature: signature, }, nil } // VerifySignature verifies the signature in given r. func VerifySignature(r *http.Request, securityHeader *ContentSecurityHeader, tolerance time.Duration) int { seconds, err := strconv.ParseInt(securityHeader.Timestamp, 10, 64) if err != nil { return httpx.CodeSignatureInvalidHeader } now := time.Now().Unix() toleranceSeconds := int64(tolerance.Seconds()) if seconds+toleranceSeconds < now || now+toleranceSeconds < seconds { return httpx.CodeSignatureWrongTime } reqPath, reqQuery := getPathQuery(r) signContent := strings.Join([]string{ securityHeader.Timestamp, r.Method, reqPath, reqQuery, computeBodySignature(r), }, "\n") actualSignature := codec.HmacBase64(securityHeader.Key, signContent) if securityHeader.Signature == actualSignature { return httpx.CodeSignaturePass } logc.Infof(r.Context(), "signature different, expect: %s, actual: %s", securityHeader.Signature, actualSignature) return httpx.CodeSignatureInvalidToken } func computeBodySignature(r *http.Request) string { var dup io.ReadCloser r.Body, dup = iox.DupReadCloser(r.Body) sha := sha256.New() io.Copy(sha, r.Body) r.Body = dup return fmt.Sprintf("%x", sha.Sum(nil)) } func getPathQuery(r *http.Request) (string, string) { requestUri := r.Header.Get(requestUriHeader) if len(requestUri) == 0 { return r.URL.Path, r.URL.RawQuery } uri, err := url.Parse(requestUri) if err != nil { return r.URL.Path, r.URL.RawQuery } return uri.Path, uri.RawQuery }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/internal/header/headers.go
rest/internal/header/headers.go
package header const ( // ApplicationJson stands for application/json. ApplicationJson = "application/json" // CacheControl is the header key for Cache-Control. CacheControl = "Cache-Control" // CacheControlNoCache is the value for Cache-Control: no-cache. CacheControlNoCache = "no-cache" // Connection is the header key for Connection. Connection = "Connection" // ConnectionKeepAlive is the value for Connection: keep-alive. ConnectionKeepAlive = "keep-alive" // ContentType is the header key for Content-Type. ContentType = "Content-Type" // ContentTypeJson is the content type for JSON. ContentTypeJson = "application/json; charset=utf-8" // ContentTypeEventStream is the content type for event stream. ContentTypeEventStream = "text/event-stream" )
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/internal/response/headeronceresponsewriter_test.go
rest/internal/response/headeronceresponsewriter_test.go
package response import ( "bufio" "net" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestHeaderOnceResponseWriter_Flush(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { cw := NewHeaderOnceResponseWriter(w) cw.Header().Set("X-Test", "test") cw.WriteHeader(http.StatusServiceUnavailable) cw.WriteHeader(http.StatusExpectationFailed) _, err := cw.Write([]byte("content")) assert.Nil(t, err) flusher, ok := cw.(http.Flusher) assert.True(t, ok) flusher.Flush() }) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusServiceUnavailable, resp.Code) assert.Equal(t, "test", resp.Header().Get("X-Test")) assert.Equal(t, "content", resp.Body.String()) } func TestHeaderOnceResponseWriter_Hijack(t *testing.T) { resp := httptest.NewRecorder() writer := &HeaderOnceResponseWriter{ w: resp, } assert.NotPanics(t, func() { writer.Hijack() }) writer = &HeaderOnceResponseWriter{ w: mockedHijackable{resp}, } assert.NotPanics(t, func() { writer.Hijack() }) } type mockedHijackable struct { *httptest.ResponseRecorder } func (m mockedHijackable) Hijack() (net.Conn, *bufio.ReadWriter, error) { return nil, nil, nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/internal/response/withcoderesponsewriter.go
rest/internal/response/withcoderesponsewriter.go
package response import ( "bufio" "errors" "net" "net/http" ) // A WithCodeResponseWriter is a helper to delay sealing a http.ResponseWriter on writing code. type WithCodeResponseWriter struct { Writer http.ResponseWriter Code int } // NewWithCodeResponseWriter returns a WithCodeResponseWriter. // If writer is already a WithCodeResponseWriter, it returns writer directly. func NewWithCodeResponseWriter(writer http.ResponseWriter) *WithCodeResponseWriter { switch w := writer.(type) { case *WithCodeResponseWriter: return w default: return &WithCodeResponseWriter{ Writer: writer, Code: http.StatusOK, } } } // Flush flushes the response writer. func (w *WithCodeResponseWriter) Flush() { if flusher, ok := w.Writer.(http.Flusher); ok { flusher.Flush() } } // Header returns the http header. func (w *WithCodeResponseWriter) Header() http.Header { return w.Writer.Header() } // Hijack implements the http.Hijacker interface. // This expands the Response to fulfill http.Hijacker if the underlying http.ResponseWriter supports it. func (w *WithCodeResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { if hijacked, ok := w.Writer.(http.Hijacker); ok { return hijacked.Hijack() } return nil, nil, errors.New("server doesn't support hijacking") } // Unwrap returns the underlying http.ResponseWriter. // This is used by http.ResponseController to unwrap the response writer. func (w *WithCodeResponseWriter) Unwrap() http.ResponseWriter { return w.Writer } // Write writes bytes into w. func (w *WithCodeResponseWriter) Write(bytes []byte) (int, error) { return w.Writer.Write(bytes) } // WriteHeader writes code into w, and not sealing the writer. func (w *WithCodeResponseWriter) WriteHeader(code int) { w.Writer.WriteHeader(code) w.Code = code }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/internal/response/headeronceresponsewriter.go
rest/internal/response/headeronceresponsewriter.go
package response import ( "bufio" "errors" "net" "net/http" ) // HeaderOnceResponseWriter is a http.ResponseWriter implementation // that only the first WriterHeader takes effect. type HeaderOnceResponseWriter struct { w http.ResponseWriter wroteHeader bool } // NewHeaderOnceResponseWriter returns a HeaderOnceResponseWriter. func NewHeaderOnceResponseWriter(w http.ResponseWriter) http.ResponseWriter { return &HeaderOnceResponseWriter{w: w} } // Flush flushes the response writer. func (w *HeaderOnceResponseWriter) Flush() { if flusher, ok := w.w.(http.Flusher); ok { flusher.Flush() } } // Header returns the http header. func (w *HeaderOnceResponseWriter) Header() http.Header { return w.w.Header() } // Hijack implements the http.Hijacker interface. // This expands the Response to fulfill http.Hijacker if the underlying http.ResponseWriter supports it. func (w *HeaderOnceResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { if hijacked, ok := w.w.(http.Hijacker); ok { return hijacked.Hijack() } return nil, nil, errors.New("server doesn't support hijacking") } // Write writes bytes into w. func (w *HeaderOnceResponseWriter) Write(bytes []byte) (int, error) { return w.w.Write(bytes) } // WriteHeader writes code into w, and not sealing the writer. func (w *HeaderOnceResponseWriter) WriteHeader(code int) { if w.wroteHeader { return } w.w.WriteHeader(code) w.wroteHeader = true }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/internal/response/withcoderesponsewriter_test.go
rest/internal/response/withcoderesponsewriter_test.go
package response import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestWithCodeResponseWriter(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { cw := NewWithCodeResponseWriter(w) cw.Header().Set("X-Test", "test") cw.WriteHeader(http.StatusServiceUnavailable) assert.Equal(t, cw.Code, http.StatusServiceUnavailable) _, err := cw.Write([]byte("content")) assert.Nil(t, err) flusher, ok := http.ResponseWriter(cw).(http.Flusher) assert.True(t, ok) flusher.Flush() }) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusServiceUnavailable, resp.Code) assert.Equal(t, "test", resp.Header().Get("X-Test")) assert.Equal(t, "content", resp.Body.String()) } func TestWithCodeResponseWriter_Hijack(t *testing.T) { resp := httptest.NewRecorder() writer := NewWithCodeResponseWriter(NewWithCodeResponseWriter(resp)) assert.NotPanics(t, func() { writer.Hijack() }) writer = &WithCodeResponseWriter{ Writer: mockedHijackable{resp}, } assert.NotPanics(t, func() { writer.Hijack() }) } func TestWithCodeResponseWriter_Unwrap(t *testing.T) { resp := httptest.NewRecorder() writer := NewWithCodeResponseWriter(resp) unwrapped := writer.Unwrap() assert.Equal(t, resp, unwrapped) // Test with a nested WithCodeResponseWriter nestedWriter := NewWithCodeResponseWriter(writer) unwrappedNested := nestedWriter.Unwrap() assert.Equal(t, resp, unwrappedNested) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/token/tokenparser.go
rest/token/tokenparser.go
package token import ( "net/http" "sync" "sync/atomic" "time" "github.com/golang-jwt/jwt/v4" "github.com/golang-jwt/jwt/v4/request" "github.com/zeromicro/go-zero/core/timex" ) const claimHistoryResetDuration = time.Hour * 24 type ( // ParseOption defines the method to customize a TokenParser. ParseOption func(parser *TokenParser) // A TokenParser is used to parse tokens. TokenParser struct { resetTime time.Duration resetDuration time.Duration history sync.Map } ) // NewTokenParser returns a TokenParser. func NewTokenParser(opts ...ParseOption) *TokenParser { parser := &TokenParser{ resetTime: timex.Now(), resetDuration: claimHistoryResetDuration, } for _, opt := range opts { opt(parser) } return parser } // ParseToken parses token from given r, with passed in secret and prevSecret. func (tp *TokenParser) ParseToken(r *http.Request, secret, prevSecret string) (*jwt.Token, error) { var token *jwt.Token var err error if len(prevSecret) > 0 { count := tp.loadCount(secret) prevCount := tp.loadCount(prevSecret) var first, second string if count > prevCount { first = secret second = prevSecret } else { first = prevSecret second = secret } token, err = tp.doParseToken(r, first) if err != nil { token, err = tp.doParseToken(r, second) if err != nil { return nil, err } tp.incrementCount(second) } else { tp.incrementCount(first) } } else { token, err = tp.doParseToken(r, secret) if err != nil { return nil, err } } return token, nil } func (tp *TokenParser) doParseToken(r *http.Request, secret string) (*jwt.Token, error) { return request.ParseFromRequest(r, request.AuthorizationHeaderExtractor, func(token *jwt.Token) (any, error) { return []byte(secret), nil }, request.WithParser(newParser())) } func (tp *TokenParser) incrementCount(secret string) { now := timex.Now() if tp.resetTime+tp.resetDuration < now { tp.history.Range(func(key, value any) bool { tp.history.Delete(key) return true }) } value, ok := tp.history.Load(secret) if ok { atomic.AddUint64(value.(*uint64), 1) } else { var count uint64 = 1 tp.history.Store(secret, &count) } } func (tp *TokenParser) loadCount(secret string) uint64 { value, ok := tp.history.Load(secret) if ok { return *value.(*uint64) } return 0 } // WithResetDuration returns a func to customize a TokenParser with reset duration. func WithResetDuration(duration time.Duration) ParseOption { return func(parser *TokenParser) { parser.resetDuration = duration } } func newParser() *jwt.Parser { return jwt.NewParser(jwt.WithJSONNumber()) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/token/tokenparser_test.go
rest/token/tokenparser_test.go
package token import ( "net/http" "net/http/httptest" "testing" "time" "github.com/golang-jwt/jwt/v4" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/timex" ) func TestTokenParser(t *testing.T) { const ( key = "14F17379-EB8F-411B-8F12-6929002DCA76" prevKey = "B63F477D-BBA3-4E52-96D3-C0034C27694A" ) keys := []struct { key string prevKey string }{ { key, prevKey, }, { key, "", }, } for _, pair := range keys { req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) token, err := buildToken(key, map[string]any{ "key": "value", }, 3600) assert.Nil(t, err) req.Header.Set("Authorization", "Bearer "+token) parser := NewTokenParser(WithResetDuration(time.Minute)) tok, err := parser.ParseToken(req, pair.key, pair.prevKey) assert.Nil(t, err) assert.Equal(t, "value", tok.Claims.(jwt.MapClaims)["key"]) } } func TestTokenParser_Expired(t *testing.T) { const ( key = "14F17379-EB8F-411B-8F12-6929002DCA76" prevKey = "B63F477D-BBA3-4E52-96D3-C0034C27694A" ) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) token, err := buildToken(key, map[string]any{ "key": "value", }, 3600) assert.Nil(t, err) req.Header.Set("Authorization", "Bearer "+token) parser := NewTokenParser(WithResetDuration(time.Second)) tok, err := parser.ParseToken(req, key, prevKey) assert.Nil(t, err) assert.Equal(t, "value", tok.Claims.(jwt.MapClaims)["key"]) tok, err = parser.ParseToken(req, key, prevKey) assert.Nil(t, err) assert.Equal(t, "value", tok.Claims.(jwt.MapClaims)["key"]) parser.resetTime = timex.Now() - time.Hour tok, err = parser.ParseToken(req, key, prevKey) assert.Nil(t, err) assert.Equal(t, "value", tok.Claims.(jwt.MapClaims)["key"]) } func buildToken(secretKey string, payloads map[string]any, seconds int64) (string, error) { now := time.Now().Unix() claims := make(jwt.MapClaims) claims["exp"] = now + seconds claims["iat"] = now for k, v := range payloads { claims[k] = v } token := jwt.New(jwt.SigningMethodHS256) token.Claims = claims return token.SignedString([]byte(secretKey)) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/router/patrouter.go
rest/router/patrouter.go
package router import ( "errors" "net/http" "path" "strings" "github.com/zeromicro/go-zero/core/search" "github.com/zeromicro/go-zero/rest/httpx" "github.com/zeromicro/go-zero/rest/pathvar" ) const ( allowHeader = "Allow" allowMethodSeparator = ", " ) var ( // ErrInvalidMethod is an error that indicates not a valid http method. ErrInvalidMethod = errors.New("not a valid http method") // ErrInvalidPath is an error that indicates path does not start with /. ErrInvalidPath = errors.New("path must begin with '/'") ) type patRouter struct { trees map[string]*search.Tree notFound http.Handler notAllowed http.Handler } // NewRouter returns a httpx.Router. func NewRouter() httpx.Router { return &patRouter{ trees: make(map[string]*search.Tree), } } func (pr *patRouter) Handle(method, reqPath string, handler http.Handler) error { if !validMethod(method) { return ErrInvalidMethod } if len(reqPath) == 0 || reqPath[0] != '/' { return ErrInvalidPath } cleanPath := path.Clean(reqPath) tree, ok := pr.trees[method] if ok { return tree.Add(cleanPath, handler) } tree = search.NewTree() pr.trees[method] = tree return tree.Add(cleanPath, handler) } func (pr *patRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) { reqPath := path.Clean(r.URL.Path) if tree, ok := pr.trees[r.Method]; ok { if result, ok := tree.Search(reqPath); ok { if len(result.Params) > 0 { r = pathvar.WithVars(r, result.Params) } result.Item.(http.Handler).ServeHTTP(w, r) return } } allows, ok := pr.methodsAllowed(r.Method, reqPath) if !ok { pr.handleNotFound(w, r) return } if pr.notAllowed != nil { pr.notAllowed.ServeHTTP(w, r) } else { w.Header().Set(allowHeader, allows) w.WriteHeader(http.StatusMethodNotAllowed) } } func (pr *patRouter) SetNotFoundHandler(handler http.Handler) { pr.notFound = handler } func (pr *patRouter) SetNotAllowedHandler(handler http.Handler) { pr.notAllowed = handler } func (pr *patRouter) handleNotFound(w http.ResponseWriter, r *http.Request) { if pr.notFound != nil { pr.notFound.ServeHTTP(w, r) } else { http.NotFound(w, r) } } func (pr *patRouter) methodsAllowed(method, path string) (string, bool) { var allows []string for treeMethod, tree := range pr.trees { if treeMethod == method { continue } _, ok := tree.Search(path) if ok { allows = append(allows, treeMethod) } } if len(allows) > 0 { return strings.Join(allows, allowMethodSeparator), true } return "", false } func validMethod(method string) bool { return method == http.MethodDelete || method == http.MethodGet || method == http.MethodHead || method == http.MethodOptions || method == http.MethodPatch || method == http.MethodPost || method == http.MethodPut }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/router/patrouter_test.go
rest/router/patrouter_test.go
package router import ( "bytes" "fmt" "io" "net/http" "net/http/httptest" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/rest/httpx" "github.com/zeromicro/go-zero/rest/internal/header" "github.com/zeromicro/go-zero/rest/pathvar" ) const contentLength = "Content-Length" type mockedResponseWriter struct { code int } func (m *mockedResponseWriter) Header() http.Header { return http.Header{} } func (m *mockedResponseWriter) Write(p []byte) (int, error) { return len(p), nil } func (m *mockedResponseWriter) WriteHeader(code int) { m.code = code } func TestPatRouterHandleErrors(t *testing.T) { tests := []struct { method string path string err error }{ {"FAKE", "", ErrInvalidMethod}, {"GET", "", ErrInvalidPath}, } for _, test := range tests { t.Run(test.method, func(t *testing.T) { router := NewRouter() err := router.Handle(test.method, test.path, nil) assert.Equal(t, test.err, err) }) } } func TestPatRouterNotFound(t *testing.T) { var notFound bool router := NewRouter() router.SetNotFoundHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { notFound = true })) err := router.Handle(http.MethodGet, "/a/b", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) assert.Nil(t, err) r, _ := http.NewRequest(http.MethodGet, "/b/c", nil) w := new(mockedResponseWriter) router.ServeHTTP(w, r) assert.True(t, notFound) } func TestPatRouterNotAllowed(t *testing.T) { var notAllowed bool router := NewRouter() router.SetNotAllowedHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { notAllowed = true })) err := router.Handle(http.MethodGet, "/a/b", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) assert.Nil(t, err) r, _ := http.NewRequest(http.MethodPost, "/a/b", nil) w := new(mockedResponseWriter) router.ServeHTTP(w, r) assert.True(t, notAllowed) } func TestPatRouter(t *testing.T) { tests := []struct { method string path string expect bool code int err error }{ // we don't explicitly set status code, framework will do it. {http.MethodGet, "/a/b", true, 0, nil}, {http.MethodGet, "/a/b/", true, 0, nil}, {http.MethodGet, "/a/b?a=b", true, 0, nil}, {http.MethodGet, "/a/b/?a=b", true, 0, nil}, {http.MethodGet, "/a/b/c?a=b", true, 0, nil}, {http.MethodGet, "/b/d", false, http.StatusNotFound, nil}, } for _, test := range tests { t.Run(test.method+":"+test.path, func(t *testing.T) { routed := false router := NewRouter() err := router.Handle(test.method, "/a/:b", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { routed = true assert.Equal(t, 1, len(pathvar.Vars(r))) })) assert.Nil(t, err) err = router.Handle(test.method, "/a/b/c", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { routed = true assert.Nil(t, pathvar.Vars(r)) })) assert.Nil(t, err) err = router.Handle(test.method, "/b/c", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { routed = true })) assert.Nil(t, err) w := new(mockedResponseWriter) r, _ := http.NewRequest(test.method, test.path, nil) router.ServeHTTP(w, r) assert.Equal(t, test.expect, routed) assert.Equal(t, test.code, w.code) if test.code == 0 { r, _ = http.NewRequest(http.MethodPut, test.path, nil) router.ServeHTTP(w, r) assert.Equal(t, http.StatusMethodNotAllowed, w.code) } }) } } func TestParseSlice(t *testing.T) { body := `names=first&names=second` reader := strings.NewReader(body) r, err := http.NewRequest(http.MethodPost, "http://hello.com/", reader) assert.Nil(t, err) r.Header.Set("Content-Type", "application/x-www-form-urlencoded") rt := NewRouter() err = rt.Handle(http.MethodPost, "/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { v := struct { Names []string `form:"names"` }{} err = httpx.Parse(r, &v) assert.Nil(t, err) assert.Equal(t, 2, len(v.Names)) assert.Equal(t, "first", v.Names[0]) assert.Equal(t, "second", v.Names[1]) })) assert.Nil(t, err) rr := httptest.NewRecorder() rt.ServeHTTP(rr, r) } func TestParseJsonPost(t *testing.T) { r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017?nickname=whatever&zipcode=200000", bytes.NewBufferString(`{"location": "shanghai", "time": 20170912}`)) assert.Nil(t, err) r.Header.Set(httpx.ContentType, httpx.JsonContentType) router := NewRouter() err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc(func( w http.ResponseWriter, r *http.Request) { v := struct { Name string `path:"name"` Year int `path:"year"` Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode"` Location string `json:"location"` Time int64 `json:"time"` }{} err = httpx.Parse(r, &v) assert.Nil(t, err) _, err = io.WriteString(w, fmt.Sprintf("%s:%d:%s:%d:%s:%d", v.Name, v.Year, v.Nickname, v.Zipcode, v.Location, v.Time)) assert.Nil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) assert.Equal(t, "kevin:2017:whatever:200000:shanghai:20170912", rr.Body.String()) } func TestParseJsonPostWithIntSlice(t *testing.T) { r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017", bytes.NewBufferString(`{"ages": [1, 2], "years": [3, 4]}`)) assert.Nil(t, err) r.Header.Set(httpx.ContentType, httpx.JsonContentType) router := NewRouter() err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc(func( w http.ResponseWriter, r *http.Request) { v := struct { Name string `path:"name"` Year int `path:"year"` Ages []int `json:"ages"` Years []int64 `json:"years"` }{} err = httpx.Parse(r, &v) assert.Nil(t, err) assert.ElementsMatch(t, []int{1, 2}, v.Ages) assert.ElementsMatch(t, []int64{3, 4}, v.Years) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) } func TestParseJsonPostError(t *testing.T) { payload := `[{"abcd": "cdef"}]` r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017?nickname=whatever&zipcode=200000", bytes.NewBufferString(payload)) assert.Nil(t, err) r.Header.Set(httpx.ContentType, httpx.JsonContentType) router := NewRouter() err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Name string `path:"name"` Year int `path:"year"` Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode"` Location string `json:"location"` Time int64 `json:"time"` }{} err = httpx.Parse(r, &v) assert.NotNil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) } func TestParseJsonPostInvalidRequest(t *testing.T) { payload := `{"ages": ["cdef"]}` r, err := http.NewRequest(http.MethodPost, "http://hello.com/", bytes.NewBufferString(payload)) assert.Nil(t, err) r.Header.Set(httpx.ContentType, httpx.JsonContentType) router := NewRouter() err = router.Handle(http.MethodPost, "/", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Ages []int `json:"ages"` }{} err = httpx.Parse(r, &v) assert.NotNil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) } func TestParseJsonPostRequired(t *testing.T) { r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017", bytes.NewBufferString(`{"location": "shanghai"`)) assert.Nil(t, err) r.Header.Set(httpx.ContentType, httpx.JsonContentType) router := NewRouter() err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Name string `path:"name"` Year int `path:"year"` Location string `json:"location"` Time int64 `json:"time"` }{} err = httpx.Parse(r, &v) assert.NotNil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) } func TestParsePath(t *testing.T) { r, err := http.NewRequest(http.MethodGet, "http://hello.com/kevin/2017", nil) assert.Nil(t, err) router := NewRouter() err = router.Handle(http.MethodGet, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Name string `path:"name"` Year int `path:"year"` }{} err = httpx.Parse(r, &v) assert.Nil(t, err) _, err = io.WriteString(w, fmt.Sprintf("%s in %d", v.Name, v.Year)) assert.Nil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) assert.Equal(t, "kevin in 2017", rr.Body.String()) } func TestParsePathRequired(t *testing.T) { r, err := http.NewRequest(http.MethodGet, "http://hello.com/kevin", nil) assert.Nil(t, err) router := NewRouter() err = router.Handle(http.MethodGet, "/:name/", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Name string `path:"name"` Year int `path:"year"` }{} err = httpx.Parse(r, &v) assert.NotNil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) } func TestParseQuery(t *testing.T) { r, err := http.NewRequest(http.MethodGet, "http://hello.com/kevin/2017?nickname=whatever&zipcode=200000", nil) assert.Nil(t, err) router := NewRouter() err = router.Handle(http.MethodGet, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode"` }{} err = httpx.Parse(r, &v) assert.Nil(t, err) _, err = io.WriteString(w, fmt.Sprintf("%s:%d", v.Nickname, v.Zipcode)) assert.Nil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) assert.Equal(t, "whatever:200000", rr.Body.String()) } func TestParseQueryRequired(t *testing.T) { r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017?nickname=whatever", nil) assert.Nil(t, err) router := NewRouter() err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { v := struct { Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode"` }{} err = httpx.Parse(r, &v) assert.NotNil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) } func TestParseOptional(t *testing.T) { r, err := http.NewRequest(http.MethodGet, "http://hello.com/kevin/2017?nickname=whatever", nil) assert.Nil(t, err) router := NewRouter() err = router.Handle(http.MethodGet, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode,optional"` }{} err = httpx.Parse(r, &v) assert.Nil(t, err) _, err = io.WriteString(w, fmt.Sprintf("%s:%d", v.Nickname, v.Zipcode)) assert.Nil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) assert.Equal(t, "whatever:0", rr.Body.String()) } func TestParseNestedInRequestEmpty(t *testing.T) { r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017", bytes.NewBufferString("{}")) assert.Nil(t, err) type ( Request struct { Name string `path:"name"` Year int `path:"year"` } Audio struct { Volume int `json:"volume"` } WrappedRequest struct { Request Audio Audio `json:"audio,optional"` } ) router := NewRouter() err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { var v WrappedRequest err = httpx.Parse(r, &v) assert.Nil(t, err) _, err = io.WriteString(w, fmt.Sprintf("%s:%d", v.Name, v.Year)) assert.Nil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) assert.Equal(t, "kevin:2017", rr.Body.String()) } func TestParsePtrInRequest(t *testing.T) { r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017", bytes.NewBufferString(`{"audio": {"volume": 100}}`)) assert.Nil(t, err) r.Header.Set(httpx.ContentType, httpx.JsonContentType) type ( Request struct { Name string `path:"name"` Year int `path:"year"` } Audio struct { Volume int `json:"volume"` } WrappedRequest struct { Request Audio *Audio `json:"audio,optional"` } ) router := NewRouter() err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { var v WrappedRequest err = httpx.Parse(r, &v) assert.Nil(t, err) _, err = io.WriteString(w, fmt.Sprintf("%s:%d:%d", v.Name, v.Year, v.Audio.Volume)) assert.Nil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) assert.Equal(t, "kevin:2017:100", rr.Body.String()) } func TestParsePtrInRequestEmpty(t *testing.T) { r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin", bytes.NewBufferString("{}")) assert.Nil(t, err) type ( Audio struct { Volume int `json:"volume"` } WrappedRequest struct { Audio *Audio `json:"audio,optional"` } ) router := NewRouter() err = router.Handle(http.MethodPost, "/kevin", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { var v WrappedRequest err = httpx.Parse(r, &v) assert.Nil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) } func TestParseQueryOptional(t *testing.T) { t.Run("optional with string", func(t *testing.T) { r, err := http.NewRequest(http.MethodGet, "http://hello.com/kevin/2017?nickname=whatever&zipcode=", nil) assert.Nil(t, err) router := NewRouter() err = router.Handle(http.MethodGet, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Nickname string `form:"nickname"` Zipcode string `form:"zipcode,optional"` }{} err = httpx.Parse(r, &v) assert.Nil(t, err) _, err = io.WriteString(w, fmt.Sprintf("%s:%s", v.Nickname, v.Zipcode)) assert.Nil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) assert.Equal(t, "whatever:", rr.Body.String()) }) t.Run("optional with int", func(t *testing.T) { r, err := http.NewRequest(http.MethodGet, "http://hello.com/kevin/2017?nickname=whatever", nil) assert.Nil(t, err) router := NewRouter() err = router.Handle(http.MethodGet, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Nickname string `form:"nickname"` Zipcode int `form:"zipcode,optional"` }{} err = httpx.Parse(r, &v) assert.Nil(t, err) _, err = io.WriteString(w, fmt.Sprintf("%s:%d", v.Nickname, v.Zipcode)) assert.Nil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) assert.Equal(t, "whatever:0", rr.Body.String()) }) } func TestParse(t *testing.T) { r, err := http.NewRequest(http.MethodGet, "http://hello.com/kevin/2017?nickname=whatever&zipcode=200000", nil) assert.Nil(t, err) router := NewRouter() err = router.Handle(http.MethodGet, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Name string `path:"name"` Year int `path:"year"` Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode"` }{} err = httpx.Parse(r, &v) assert.Nil(t, err) _, err = io.WriteString(w, fmt.Sprintf("%s:%d:%s:%d", v.Name, v.Year, v.Nickname, v.Zipcode)) assert.Nil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) assert.Equal(t, "kevin:2017:whatever:200000", rr.Body.String()) } func TestParseWrappedRequest(t *testing.T) { r, err := http.NewRequest(http.MethodGet, "http://hello.com/kevin/2017", nil) assert.Nil(t, err) type ( Request struct { Name string `path:"name"` Year int `path:"year"` } WrappedRequest struct { Request } ) router := NewRouter() err = router.Handle(http.MethodGet, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { var v WrappedRequest err = httpx.Parse(r, &v) assert.Nil(t, err) _, err = io.WriteString(w, fmt.Sprintf("%s:%d", v.Name, v.Year)) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) assert.Equal(t, "kevin:2017", rr.Body.String()) } func TestParseWrappedGetRequestWithJsonHeader(t *testing.T) { r, err := http.NewRequest(http.MethodGet, "http://hello.com/kevin/2017", bytes.NewReader(nil)) assert.Nil(t, err) r.Header.Set(httpx.ContentType, header.ContentTypeJson) type ( Request struct { Name string `path:"name"` Year int `path:"year"` } WrappedRequest struct { Request } ) router := NewRouter() err = router.Handle(http.MethodGet, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { var v WrappedRequest err = httpx.Parse(r, &v) assert.Nil(t, err) _, err = io.WriteString(w, fmt.Sprintf("%s:%d", v.Name, v.Year)) assert.Nil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) assert.Equal(t, "kevin:2017", rr.Body.String()) } func TestParseWrappedHeadRequestWithJsonHeader(t *testing.T) { r, err := http.NewRequest(http.MethodHead, "http://hello.com/kevin/2017", bytes.NewReader(nil)) assert.Nil(t, err) r.Header.Set(httpx.ContentType, header.ContentTypeJson) type ( Request struct { Name string `path:"name"` Year int `path:"year"` } WrappedRequest struct { Request } ) router := NewRouter() err = router.Handle(http.MethodHead, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { var v WrappedRequest err = httpx.Parse(r, &v) assert.Nil(t, err) _, err = io.WriteString(w, fmt.Sprintf("%s:%d", v.Name, v.Year)) assert.Nil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) assert.Equal(t, "kevin:2017", rr.Body.String()) } func TestParseWrappedRequestPtr(t *testing.T) { r, err := http.NewRequest(http.MethodGet, "http://hello.com/kevin/2017", nil) assert.Nil(t, err) type ( Request struct { Name string `path:"name"` Year int `path:"year"` } WrappedRequest struct { *Request } ) router := NewRouter() err = router.Handle(http.MethodGet, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { var v WrappedRequest err = httpx.Parse(r, &v) assert.Nil(t, err) _, err = io.WriteString(w, fmt.Sprintf("%s:%d", v.Name, v.Year)) assert.Nil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) assert.Equal(t, "kevin:2017", rr.Body.String()) } func TestParseWithAll(t *testing.T) { r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017?nickname=whatever&zipcode=200000", bytes.NewBufferString(`{"location": "shanghai", "time": 20170912}`)) assert.Nil(t, err) r.Header.Set(httpx.ContentType, httpx.JsonContentType) router := NewRouter() err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { v := struct { Name string `path:"name"` Year int `path:"year"` Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode"` Location string `json:"location"` Time int64 `json:"time"` }{} err = httpx.Parse(r, &v) assert.Nil(t, err) _, err = io.WriteString(w, fmt.Sprintf("%s:%d:%s:%d:%s:%d", v.Name, v.Year, v.Nickname, v.Zipcode, v.Location, v.Time)) assert.Nil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) assert.Equal(t, "kevin:2017:whatever:200000:shanghai:20170912", rr.Body.String()) } func TestParseWithAllUtf8(t *testing.T) { r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017?nickname=whatever&zipcode=200000", bytes.NewBufferString(`{"location": "shanghai", "time": 20170912}`)) assert.Nil(t, err) r.Header.Set(httpx.ContentType, header.ContentTypeJson) router := NewRouter() err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Name string `path:"name"` Year int `path:"year"` Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode"` Location string `json:"location"` Time int64 `json:"time"` }{} err = httpx.Parse(r, &v) assert.Nil(t, err) _, err = io.WriteString(w, fmt.Sprintf("%s:%d:%s:%d:%s:%d", v.Name, v.Year, v.Nickname, v.Zipcode, v.Location, v.Time)) assert.Nil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) assert.Equal(t, "kevin:2017:whatever:200000:shanghai:20170912", rr.Body.String()) } func TestParseWithMissingForm(t *testing.T) { r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017?nickname=whatever", bytes.NewBufferString(`{"location": "shanghai", "time": 20170912}`)) assert.Nil(t, err) router := NewRouter() err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Name string `path:"name"` Year int `path:"year"` Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode"` Location string `json:"location"` Time int64 `json:"time"` }{} err = httpx.Parse(r, &v) assert.NotNil(t, err) assert.Equal(t, `field "zipcode" is not set`, err.Error()) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) } func TestParseWithMissingAllForms(t *testing.T) { r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017", bytes.NewBufferString(`{"location": "shanghai", "time": 20170912}`)) assert.Nil(t, err) router := NewRouter() err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Name string `path:"name"` Year int `path:"year"` Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode"` Location string `json:"location"` Time int64 `json:"time"` }{} err = httpx.Parse(r, &v) assert.NotNil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) } func TestParseWithMissingJson(t *testing.T) { r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017?nickname=whatever&zipcode=200000", bytes.NewBufferString(`{"location": "shanghai"}`)) assert.Nil(t, err) router := NewRouter() err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Name string `path:"name"` Year int `path:"year"` Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode"` Location string `json:"location"` Time int64 `json:"time"` }{} err = httpx.Parse(r, &v) assert.NotEqual(t, io.EOF, err) assert.NotNil(t, httpx.Parse(r, &v)) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) } func TestParseWithMissingAllJsons(t *testing.T) { r, err := http.NewRequest(http.MethodGet, "http://hello.com/kevin/2017?nickname=whatever&zipcode=200000", nil) assert.Nil(t, err) router := NewRouter() err = router.Handle(http.MethodGet, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Name string `path:"name"` Year int `path:"year"` Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode"` Location string `json:"location"` Time int64 `json:"time"` }{} err = httpx.Parse(r, &v) assert.NotEqual(t, io.EOF, err) assert.NotNil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) } func TestParseWithMissingPath(t *testing.T) { r, err := http.NewRequest(http.MethodPost, "http://hello.com/2017?nickname=whatever&zipcode=200000", bytes.NewBufferString(`{"location": "shanghai", "time": 20170912}`)) assert.Nil(t, err) router := NewRouter() err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Name string `path:"name"` Year int `path:"year"` Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode"` Location string `json:"location"` Time int64 `json:"time"` }{} err = httpx.Parse(r, &v) assert.NotNil(t, err) assert.Equal(t, "field name is not set", err.Error()) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) } func TestParseWithMissingAllPaths(t *testing.T) { r, err := http.NewRequest(http.MethodPost, "http://hello.com/?nickname=whatever&zipcode=200000", bytes.NewBufferString(`{"location": "shanghai", "time": 20170912}`)) assert.Nil(t, err) router := NewRouter() err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Name string `path:"name"` Year int `path:"year"` Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode"` Location string `json:"location"` Time int64 `json:"time"` }{} err = httpx.Parse(r, &v) assert.NotNil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) } func TestParseGetWithContentLengthHeader(t *testing.T) { r, err := http.NewRequest(http.MethodGet, "http://hello.com/kevin/2017?nickname=whatever&zipcode=200000", nil) assert.Nil(t, err) r.Header.Set(httpx.ContentType, header.ContentTypeJson) r.Header.Set(contentLength, "1024") router := NewRouter() err = router.Handle(http.MethodGet, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Name string `path:"name"` Year int `path:"year"` Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode"` Location string `json:"location"` Time int64 `json:"time"` }{} err = httpx.Parse(r, &v) assert.NotNil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) } func TestParseJsonPostWithTypeMismatch(t *testing.T) { r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017?nickname=whatever&zipcode=200000", bytes.NewBufferString(`{"time": "20170912"}`)) assert.Nil(t, err) r.Header.Set(httpx.ContentType, header.ContentTypeJson) router := NewRouter() err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Name string `path:"name"` Year int `path:"year"` Nickname string `form:"nickname"` Zipcode int64 `form:"zipcode"` Time int64 `json:"time"` }{} err = httpx.Parse(r, &v) assert.NotNil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) } func TestParseJsonPostWithInt2String(t *testing.T) { r, err := http.NewRequest(http.MethodPost, "http://hello.com/kevin/2017", bytes.NewBufferString(`{"time": 20170912}`)) assert.Nil(t, err) r.Header.Set(httpx.ContentType, header.ContentTypeJson) router := NewRouter() err = router.Handle(http.MethodPost, "/:name/:year", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { v := struct { Name string `path:"name"` Year int `path:"year"` Time string `json:"time"` }{} err = httpx.Parse(r, &v) assert.NotNil(t, err) })) assert.Nil(t, err) rr := httptest.NewRecorder() router.ServeHTTP(rr, r) } func BenchmarkPatRouter(b *testing.B) { b.ReportAllocs() router := NewRouter() router.Handle(http.MethodGet, "/api/:user/:name", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { })) w := &mockedResponseWriter{} r, _ := http.NewRequest(http.MethodGet, "/api/a/b", nil) for i := 0; i < b.N; i++ { router.ServeHTTP(w, r) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/maxconnshandler.go
rest/handler/maxconnshandler.go
package handler import ( "net/http" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/syncx" "github.com/zeromicro/go-zero/rest/internal" ) // MaxConnsHandler returns a middleware that limit the concurrent connections. func MaxConnsHandler(n int) func(http.Handler) http.Handler { if n <= 0 { return func(next http.Handler) http.Handler { return next } } return func(next http.Handler) http.Handler { latch := syncx.NewLimit(n) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if latch.TryBorrow() { defer func() { if err := latch.Return(); err != nil { logx.WithContext(r.Context()).Error(err) } }() next.ServeHTTP(w, r) } else { internal.Errorf(r, "concurrent connections over %d, rejected with code %d", n, http.StatusServiceUnavailable) w.WriteHeader(http.StatusServiceUnavailable) } }) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/loghandler.go
rest/handler/loghandler.go
package handler import ( "bufio" "bytes" "errors" "fmt" "io" "net" "net/http" "net/http/httputil" "strconv" "time" "github.com/zeromicro/go-zero/core/color" "github.com/zeromicro/go-zero/core/iox" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/syncx" "github.com/zeromicro/go-zero/core/timex" "github.com/zeromicro/go-zero/core/utils" "github.com/zeromicro/go-zero/rest/httpx" "github.com/zeromicro/go-zero/rest/internal" "github.com/zeromicro/go-zero/rest/internal/response" ) const ( limitBodyBytes = 1024 limitDetailedBodyBytes = 4096 defaultSlowThreshold = time.Millisecond * 500 defaultSSESlowThreshold = time.Minute * 3 ) var ( slowThreshold = syncx.ForAtomicDuration(defaultSlowThreshold) sseSlowThreshold = syncx.ForAtomicDuration(defaultSSESlowThreshold) ) // LogHandler returns a middleware that logs http request and response. func LogHandler(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { timer := utils.NewElapsedTimer() logs := new(internal.LogCollector) lrw := response.NewWithCodeResponseWriter(w) var dup io.ReadCloser r.Body, dup = iox.LimitDupReadCloser(r.Body, limitBodyBytes) next.ServeHTTP(lrw, r.WithContext(internal.WithLogCollector(r.Context(), logs))) r.Body = dup logBrief(r, lrw.Code, timer, logs) }) } type detailLoggedResponseWriter struct { writer *response.WithCodeResponseWriter buf *bytes.Buffer } func newDetailLoggedResponseWriter(writer *response.WithCodeResponseWriter, buf *bytes.Buffer) *detailLoggedResponseWriter { return &detailLoggedResponseWriter{ writer: writer, buf: buf, } } func (w *detailLoggedResponseWriter) Flush() { w.writer.Flush() } func (w *detailLoggedResponseWriter) Header() http.Header { return w.writer.Header() } // Hijack implements the http.Hijacker interface. // This expands the Response to fulfill http.Hijacker if the underlying http.ResponseWriter supports it. func (w *detailLoggedResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { if hijacked, ok := w.writer.Writer.(http.Hijacker); ok { return hijacked.Hijack() } return nil, nil, errors.New("server doesn't support hijacking") } func (w *detailLoggedResponseWriter) Write(bs []byte) (int, error) { w.buf.Write(bs) return w.writer.Write(bs) } func (w *detailLoggedResponseWriter) WriteHeader(code int) { w.writer.WriteHeader(code) } // DetailedLogHandler returns a middleware that logs http request and response in details. func DetailedLogHandler(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { timer := utils.NewElapsedTimer() var buf bytes.Buffer rw := response.NewWithCodeResponseWriter(w) lrw := newDetailLoggedResponseWriter(rw, &buf) var dup io.ReadCloser // https://github.com/zeromicro/go-zero/issues/3564 r.Body, dup = iox.LimitDupReadCloser(r.Body, limitDetailedBodyBytes) logs := new(internal.LogCollector) next.ServeHTTP(lrw, r.WithContext(internal.WithLogCollector(r.Context(), logs))) r.Body = dup logDetails(r, lrw, timer, logs) }) } // SetSlowThreshold sets the slow threshold. func SetSlowThreshold(threshold time.Duration) { slowThreshold.Set(threshold) } // SetSSESlowThreshold sets the slow threshold for SSE requests. func SetSSESlowThreshold(threshold time.Duration) { sseSlowThreshold.Set(threshold) } func dumpRequest(r *http.Request) string { reqContent, err := httputil.DumpRequest(r, true) if err != nil { return err.Error() } return string(reqContent) } func getSlowThreshold(r *http.Request) time.Duration { if r.Header.Get(headerAccept) == valueSSE { return sseSlowThreshold.Load() } else { return slowThreshold.Load() } } func isOkResponse(code int) bool { // not server error return code < http.StatusInternalServerError } func logBrief(r *http.Request, code int, timer *utils.ElapsedTimer, logs *internal.LogCollector) { var buf bytes.Buffer duration := timer.Duration() logger := logx.WithContext(r.Context()).WithDuration(duration) buf.WriteString(fmt.Sprintf("[HTTP] %s - %s %s - %s - %s", wrapStatusCode(code), wrapMethod(r.Method), r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent())) if duration > getSlowThreshold(r) { logger.Slowf("[HTTP] %s - %s %s - %s - %s - slowcall(%s)", wrapStatusCode(code), wrapMethod(r.Method), r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent(), timex.ReprOfDuration(duration)) } ok := isOkResponse(code) if !ok { buf.WriteString(fmt.Sprintf("\n%s", dumpRequest(r))) } body := logs.Flush() if len(body) > 0 { buf.WriteString(fmt.Sprintf("\n%s", body)) } if ok { logger.Info(buf.String()) } else { logger.Error(buf.String()) } } func logDetails(r *http.Request, response *detailLoggedResponseWriter, timer *utils.ElapsedTimer, logs *internal.LogCollector) { var buf bytes.Buffer duration := timer.Duration() code := response.writer.Code logger := logx.WithContext(r.Context()) buf.WriteString(fmt.Sprintf("[HTTP] %s - %d - %s - %s\n=> %s\n", r.Method, code, r.RemoteAddr, timex.ReprOfDuration(duration), dumpRequest(r))) if duration > getSlowThreshold(r) { logger.Slowf("[HTTP] %s - %d - %s - slowcall(%s)\n=> %s\n", r.Method, code, r.RemoteAddr, timex.ReprOfDuration(duration), dumpRequest(r)) } body := logs.Flush() if len(body) > 0 { buf.WriteString(fmt.Sprintf("%s\n", body)) } respBuf := response.buf.Bytes() if len(respBuf) > 0 { buf.WriteString(fmt.Sprintf("<= %s", respBuf)) } if isOkResponse(code) { logger.Info(buf.String()) } else { logger.Error(buf.String()) } } func wrapMethod(method string) string { var colour color.Color switch method { case http.MethodGet: colour = color.BgBlue case http.MethodPost: colour = color.BgCyan case http.MethodPut: colour = color.BgYellow case http.MethodDelete: colour = color.BgRed case http.MethodPatch: colour = color.BgGreen case http.MethodHead: colour = color.BgMagenta case http.MethodOptions: colour = color.BgWhite } if colour == color.NoColor { return method } return logx.WithColorPadding(method, colour) } func wrapStatusCode(code int) string { var colour color.Color switch { case code >= http.StatusOK && code < http.StatusMultipleChoices: colour = color.BgGreen case code >= http.StatusMultipleChoices && code < http.StatusBadRequest: colour = color.BgBlue case code >= http.StatusBadRequest && code < http.StatusInternalServerError: colour = color.BgMagenta default: colour = color.BgYellow } return logx.WithColorPadding(strconv.Itoa(code), colour) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/maxbyteshandler.go
rest/handler/maxbyteshandler.go
package handler import ( "net/http" "github.com/zeromicro/go-zero/rest/internal" ) // MaxBytesHandler returns a middleware that limit reading of http request body. func MaxBytesHandler(n int64) func(http.Handler) http.Handler { if n <= 0 { return func(next http.Handler) http.Handler { return next } } return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.ContentLength > n { internal.Errorf(r, "request entity too large, limit is %d, but got %d, rejected with code %d", n, r.ContentLength, http.StatusRequestEntityTooLarge) w.WriteHeader(http.StatusRequestEntityTooLarge) } else { next.ServeHTTP(w, r) } }) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/maxconnshandler_test.go
rest/handler/maxconnshandler_test.go
package handler import ( "net/http" "net/http/httptest" "sync" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/lang" ) const conns = 4 func TestMaxConnsHandler(t *testing.T) { var waitGroup sync.WaitGroup waitGroup.Add(conns) done := make(chan lang.PlaceholderType) defer close(done) maxConns := MaxConnsHandler(conns) handler := maxConns(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { waitGroup.Done() <-done })) for i := 0; i < conns; i++ { go func() { req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) handler.ServeHTTP(httptest.NewRecorder(), req) }() } waitGroup.Wait() req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusServiceUnavailable, resp.Code) } func TestWithoutMaxConnsHandler(t *testing.T) { const ( key = "block" value = "1" ) var waitGroup sync.WaitGroup waitGroup.Add(conns) done := make(chan lang.PlaceholderType) defer close(done) maxConns := MaxConnsHandler(0) handler := maxConns(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { val := r.Header.Get(key) if val == value { waitGroup.Done() <-done } })) for i := 0; i < conns; i++ { go func() { req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) req.Header.Set(key, value) handler.ServeHTTP(httptest.NewRecorder(), req) }() } waitGroup.Wait() req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/prometheushandler_test.go
rest/handler/prometheushandler_test.go
package handler import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/prometheus" ) func TestPromMetricHandler_Disabled(t *testing.T) { promMetricHandler := PrometheusHandler("/user/login", http.MethodGet) handler := promMetricHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) } func TestPromMetricHandler_Enabled(t *testing.T) { prometheus.StartAgent(prometheus.Config{ Host: "localhost", Path: "/", }) promMetricHandler := PrometheusHandler("/user/login", http.MethodGet) handler := promMetricHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/prometheushandler.go
rest/handler/prometheushandler.go
package handler import ( "net/http" "strconv" "github.com/zeromicro/go-zero/core/metric" "github.com/zeromicro/go-zero/core/timex" "github.com/zeromicro/go-zero/rest/internal/response" ) const serverNamespace = "http_server" var ( metricServerReqDur = metric.NewHistogramVec(&metric.HistogramVecOpts{ Namespace: serverNamespace, Subsystem: "requests", Name: "duration_ms", Help: "http server requests duration(ms).", Labels: []string{"path", "method", "code"}, Buckets: []float64{5, 10, 25, 50, 100, 250, 500, 750, 1000}, }) metricServerReqCodeTotal = metric.NewCounterVec(&metric.CounterVecOpts{ Namespace: serverNamespace, Subsystem: "requests", Name: "code_total", Help: "http server requests error count.", Labels: []string{"path", "method", "code"}, }) ) // PrometheusHandler returns a middleware that reports stats to prometheus. func PrometheusHandler(path, method string) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { startTime := timex.Now() cw := response.NewWithCodeResponseWriter(w) defer func() { code := strconv.Itoa(cw.Code) metricServerReqDur.Observe(timex.Since(startTime).Milliseconds(), path, method, code) metricServerReqCodeTotal.Inc(path, method, code) }() next.ServeHTTP(cw, r) }) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/recoverhandler_test.go
rest/handler/recoverhandler_test.go
package handler import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestWithPanic(t *testing.T) { handler := RecoverHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { panic("whatever") })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusInternalServerError, resp.Code) } func TestWithoutPanic(t *testing.T) { handler := RecoverHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/sheddinghandler.go
rest/handler/sheddinghandler.go
package handler import ( "net/http" "sync" "github.com/zeromicro/go-zero/core/load" "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/core/stat" "github.com/zeromicro/go-zero/rest/httpx" "github.com/zeromicro/go-zero/rest/internal/response" ) const serviceType = "api" var ( sheddingStat *load.SheddingStat lock sync.Mutex ) // SheddingHandler returns a middleware that does load shedding. func SheddingHandler(shedder load.Shedder, metrics *stat.Metrics) func(http.Handler) http.Handler { if shedder == nil { return func(next http.Handler) http.Handler { return next } } ensureSheddingStat() return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { sheddingStat.IncrementTotal() promise, err := shedder.Allow() if err != nil { metrics.AddDrop() sheddingStat.IncrementDrop() logc.Errorf(r.Context(), "[http] dropped, %s - %s - %s", r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent()) w.WriteHeader(http.StatusServiceUnavailable) return } cw := response.NewWithCodeResponseWriter(w) defer func() { if cw.Code == http.StatusServiceUnavailable { promise.Fail() } else { sheddingStat.IncrementPass() promise.Pass() } }() next.ServeHTTP(cw, r) }) } } func ensureSheddingStat() { lock.Lock() if sheddingStat == nil { sheddingStat = load.NewSheddingStat(serviceType) } lock.Unlock() }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/contentsecurityhandler_test.go
rest/handler/contentsecurityhandler_test.go
package handler import ( "bytes" "crypto/sha256" "encoding/base64" "fmt" "io" "log" "net/http" "net/http/httptest" "net/url" "os" "strconv" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/codec" "github.com/zeromicro/go-zero/rest/httpx" ) const timeDiff = time.Hour * 2 * 24 var ( fingerprint = "12345" pubKey = []byte(`-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD7bq4FLG0ctccbEFEsUBuRxkjE eJ5U+0CAEjJk20V9/u2Fu76i1oKoShCs7GXtAFbDb5A/ImIXkPY62nAaxTGK4KVH miYbRgh5Fy6336KepLCtCmV/r0PKZeCyJH9uYLs7EuE1z9Hgm5UUjmpHDhJtkAwR my47YlhspwszKdRP+wIDAQAB -----END PUBLIC KEY-----`) priKey = []byte(`-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQD7bq4FLG0ctccbEFEsUBuRxkjEeJ5U+0CAEjJk20V9/u2Fu76i 1oKoShCs7GXtAFbDb5A/ImIXkPY62nAaxTGK4KVHmiYbRgh5Fy6336KepLCtCmV/ r0PKZeCyJH9uYLs7EuE1z9Hgm5UUjmpHDhJtkAwRmy47YlhspwszKdRP+wIDAQAB AoGBANs1qf7UtuSbD1ZnKX5K8V5s07CHwPMygw+lzc3k5ndtNUStZQ2vnAaBXHyH Nm4lJ4AI2mhQ39jQB/1TyP1uAzvpLhT60fRybEq9zgJ/81Gm9bnaEpFJ9bP2bBrY J0jbaTMfbzL/PJFl3J3RGMR40C76h5yRYSnOpMoMiKWnJqrhAkEA/zCOkR+34Pk0 Yo3sIP4ranY6AAvwacgNaui4ll5xeYwv3iLOQvPlpxIxFHKXEY0klNNyjjXqgYjP cOenqtt6UwJBAPw7EYuteVHvHvQVuTbKAaYHcOrp4nFeZF3ndFfl0w2dwGhfzcXO ROyd5dNQCuCWRo8JBpjG6PFyzezayF4KLrkCQCGditoxHG7FRRJKcbVy5dMzWbaR 3AyDLslLeK1OKZKCVffkC9mj+TeF3PM9mQrV1eDI7ckv7wE7PWA5E8wc90MCQEOV MCZU3OTvRUPxbicYCUkLRV4sPNhTimD+21WR5vMHCb7trJ0Ln7wmsqXkFIYIve8l Y/cblN7c/AAyvu0znUECQA318nPldsxR6+H8HTS3uEbkL4UJdjQJHsvTwKxAw5qc moKExvRlN0zmGGuArKcqS38KG7PXZMrUv3FXPdp6BDQ= -----END RSA PRIVATE KEY-----`) key = []byte("q4t7w!z%C*F-JaNdRgUjXn2r5u8x/A?D") ) type requestSettings struct { method string url string body io.Reader strict bool crypt bool requestUri string timestamp int64 fingerprint string missHeader bool signature string } func TestContentSecurityHandler(t *testing.T) { tests := []struct { method string url string body string strict bool crypt bool requestUri string timestamp int64 fingerprint string missHeader bool signature string statusCode int }{ { method: http.MethodGet, url: "http://localhost/a/b?c=d&e=f", strict: true, crypt: false, }, { method: http.MethodPost, url: "http://localhost/a/b?c=d&e=f", body: "hello", strict: true, crypt: false, }, { method: http.MethodGet, url: "http://localhost/a/b?c=d&e=f", strict: true, crypt: true, }, { method: http.MethodPost, url: "http://localhost/a/b?c=d&e=f", body: "hello", strict: true, crypt: true, }, { method: http.MethodGet, url: "http://localhost/a/b?c=d&e=f", strict: true, crypt: true, timestamp: time.Now().Add(timeDiff).Unix(), statusCode: http.StatusForbidden, }, { method: http.MethodPost, url: "http://localhost/a/b?c=d&e=f", body: "hello", strict: true, crypt: true, timestamp: time.Now().Add(-timeDiff).Unix(), statusCode: http.StatusForbidden, }, { method: http.MethodPost, url: "http://remotehost/", body: "hello", strict: true, crypt: true, requestUri: "http://localhost/a/b?c=d&e=f", }, { method: http.MethodPost, url: "http://localhost/a/b?c=d&e=f", body: "hello", strict: false, crypt: true, fingerprint: "badone", }, { method: http.MethodPost, url: "http://localhost/a/b?c=d&e=f", body: "hello", strict: true, crypt: true, timestamp: time.Now().Add(-timeDiff).Unix(), fingerprint: "badone", statusCode: http.StatusForbidden, }, { method: http.MethodPost, url: "http://localhost/a/b?c=d&e=f", body: "hello", strict: true, crypt: true, missHeader: true, statusCode: http.StatusForbidden, }, { method: http.MethodHead, url: "http://localhost/a/b?c=d&e=f", strict: true, crypt: false, }, { method: http.MethodGet, url: "http://localhost/a/b?c=d&e=f", strict: true, crypt: false, signature: "badone", statusCode: http.StatusForbidden, }, } for _, test := range tests { t.Run(test.url, func(t *testing.T) { if test.statusCode == 0 { test.statusCode = http.StatusOK } if len(test.fingerprint) == 0 { test.fingerprint = fingerprint } if test.timestamp == 0 { test.timestamp = time.Now().Unix() } func() { keyFile, err := createTempFile(priKey) defer os.Remove(keyFile) assert.Nil(t, err) decrypter, err := codec.NewRsaDecrypter(keyFile) assert.Nil(t, err) contentSecurityHandler := ContentSecurityHandler(map[string]codec.RsaDecrypter{ fingerprint: decrypter, }, time.Hour, test.strict) handler := contentSecurityHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { })) var reader io.Reader if len(test.body) > 0 { reader = strings.NewReader(test.body) } setting := requestSettings{ method: test.method, url: test.url, body: reader, strict: test.strict, crypt: test.crypt, requestUri: test.requestUri, timestamp: test.timestamp, fingerprint: test.fingerprint, missHeader: test.missHeader, signature: test.signature, } req, err := buildRequest(setting) assert.Nil(t, err) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, test.statusCode, resp.Code) }() }) } } func TestContentSecurityHandler_UnsignedCallback(t *testing.T) { keyFile, err := createTempFile(priKey) defer os.Remove(keyFile) assert.Nil(t, err) decrypter, err := codec.NewRsaDecrypter(keyFile) assert.Nil(t, err) contentSecurityHandler := ContentSecurityHandler( map[string]codec.RsaDecrypter{ fingerprint: decrypter, }, time.Hour, true, func(w http.ResponseWriter, r *http.Request, next http.Handler, strict bool, code int) { w.WriteHeader(http.StatusOK) }) handler := contentSecurityHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) setting := requestSettings{ method: http.MethodGet, url: "http://localhost/a/b?c=d&e=f", signature: "badone", } req, err := buildRequest(setting) assert.Nil(t, err) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) } func TestContentSecurityHandler_UnsignedCallback_WrongTime(t *testing.T) { keyFile, err := createTempFile(priKey) defer os.Remove(keyFile) assert.Nil(t, err) decrypter, err := codec.NewRsaDecrypter(keyFile) assert.Nil(t, err) contentSecurityHandler := ContentSecurityHandler( map[string]codec.RsaDecrypter{ fingerprint: decrypter, }, time.Hour, true, func(w http.ResponseWriter, r *http.Request, next http.Handler, strict bool, code int) { assert.Equal(t, httpx.CodeSignatureWrongTime, code) w.WriteHeader(http.StatusOK) }) handler := contentSecurityHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) reader := strings.NewReader("hello") setting := requestSettings{ method: http.MethodPost, url: "http://localhost/a/b?c=d&e=f", body: reader, strict: true, crypt: true, timestamp: time.Now().Add(time.Hour * 24 * 365).Unix(), fingerprint: fingerprint, } req, err := buildRequest(setting) assert.Nil(t, err) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) } func buildRequest(rs requestSettings) (*http.Request, error) { var bodyStr string var err error if rs.crypt && rs.body != nil { var buf bytes.Buffer io.Copy(&buf, rs.body) bodyBytes, err := codec.EcbEncrypt(key, buf.Bytes()) if err != nil { return nil, err } bodyStr = base64.StdEncoding.EncodeToString(bodyBytes) } r := httptest.NewRequest(rs.method, rs.url, strings.NewReader(bodyStr)) if len(rs.signature) == 0 { sha := sha256.New() sha.Write([]byte(bodyStr)) bodySign := fmt.Sprintf("%x", sha.Sum(nil)) var path string var query string if len(rs.requestUri) > 0 { u, err := url.Parse(rs.requestUri) if err != nil { return nil, err } path = u.Path query = u.RawQuery } else { path = r.URL.Path query = r.URL.RawQuery } contentOfSign := strings.Join([]string{ strconv.FormatInt(rs.timestamp, 10), rs.method, path, query, bodySign, }, "\n") rs.signature = codec.HmacBase64(key, contentOfSign) } var mode string if rs.crypt { mode = "1" } else { mode = "0" } content := strings.Join([]string{ "version=v1", "type=" + mode, fmt.Sprintf("key=%s", base64.StdEncoding.EncodeToString(key)), "time=" + strconv.FormatInt(rs.timestamp, 10), }, "; ") encrypter, err := codec.NewRsaEncrypter(pubKey) if err != nil { log.Fatal(err) } output, err := encrypter.Encrypt([]byte(content)) if err != nil { log.Fatal(err) } encryptedContent := base64.StdEncoding.EncodeToString(output) if !rs.missHeader { r.Header.Set(httpx.ContentSecurity, strings.Join([]string{ fmt.Sprintf("key=%s", rs.fingerprint), "secret=" + encryptedContent, "signature=" + rs.signature, }, "; ")) } if len(rs.requestUri) > 0 { r.Header.Set("X-Request-Uri", rs.requestUri) } return r, nil } func createTempFile(body []byte) (string, error) { tmpFile, err := os.CreateTemp(os.TempDir(), "go-unit-*.tmp") if err != nil { return "", err } tmpFile.Close() if err = os.WriteFile(tmpFile.Name(), body, os.ModePerm); err != nil { return "", err } return tmpFile.Name(), nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/contentsecurityhandler.go
rest/handler/contentsecurityhandler.go
package handler import ( "net/http" "time" "github.com/zeromicro/go-zero/core/codec" "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/rest/httpx" "github.com/zeromicro/go-zero/rest/internal/security" ) const contentSecurity = "X-Content-Security" // UnsignedCallback defines the method of the unsigned callback. type UnsignedCallback func(w http.ResponseWriter, r *http.Request, next http.Handler, strict bool, code int) // ContentSecurityHandler returns a middleware to verify content security. func ContentSecurityHandler(decrypters map[string]codec.RsaDecrypter, tolerance time.Duration, strict bool, callbacks ...UnsignedCallback) func(http.Handler) http.Handler { return LimitContentSecurityHandler(maxBytes, decrypters, tolerance, strict, callbacks...) } // LimitContentSecurityHandler returns a middleware to verify content security. func LimitContentSecurityHandler(limitBytes int64, decrypters map[string]codec.RsaDecrypter, tolerance time.Duration, strict bool, callbacks ...UnsignedCallback) func(http.Handler) http.Handler { if len(callbacks) == 0 { callbacks = append(callbacks, handleVerificationFailure) } return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodDelete, http.MethodGet, http.MethodPost, http.MethodPut: header, err := security.ParseContentSecurity(decrypters, r) if err != nil { logc.Errorf(r.Context(), "Signature parse failed, X-Content-Security: %s, error: %s", r.Header.Get(contentSecurity), err.Error()) executeCallbacks(w, r, next, strict, httpx.CodeSignatureInvalidHeader, callbacks) } else if code := security.VerifySignature(r, header, tolerance); code != httpx.CodeSignaturePass { logc.Errorf(r.Context(), "Signature verification failed, X-Content-Security: %s", r.Header.Get(contentSecurity)) executeCallbacks(w, r, next, strict, code, callbacks) } else if r.ContentLength > 0 && header.Encrypted() { LimitCryptionHandler(limitBytes, header.Key)(next).ServeHTTP(w, r) } else { next.ServeHTTP(w, r) } default: next.ServeHTTP(w, r) } }) } } func executeCallbacks(w http.ResponseWriter, r *http.Request, next http.Handler, strict bool, code int, callbacks []UnsignedCallback) { for _, callback := range callbacks { callback(w, r, next, strict, code) } } func handleVerificationFailure(w http.ResponseWriter, r *http.Request, next http.Handler, strict bool, _ int) { if strict { w.WriteHeader(http.StatusForbidden) } else { next.ServeHTTP(w, r) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/breakerhandler.go
rest/handler/breakerhandler.go
package handler import ( "fmt" "net/http" "strings" "github.com/zeromicro/go-zero/core/breaker" "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/core/stat" "github.com/zeromicro/go-zero/rest/httpx" "github.com/zeromicro/go-zero/rest/internal/response" ) const breakerSeparator = "://" // BreakerHandler returns a break circuit middleware. func BreakerHandler(method, path string, metrics *stat.Metrics) func(http.Handler) http.Handler { brk := breaker.NewBreaker(breaker.WithName(strings.Join([]string{method, path}, breakerSeparator))) return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { promise, err := brk.Allow() if err != nil { metrics.AddDrop() logc.Errorf(r.Context(), "[http] dropped, %s - %s - %s", r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent()) w.WriteHeader(http.StatusServiceUnavailable) return } cw := response.NewWithCodeResponseWriter(w) defer func() { if cw.Code < http.StatusInternalServerError { promise.Accept() } else { promise.Reject(fmt.Sprintf("%d %s", cw.Code, http.StatusText(cw.Code))) } }() next.ServeHTTP(cw, r) }) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/tracehandler.go
rest/handler/tracehandler.go
package handler import ( "net/http" "github.com/zeromicro/go-zero/core/collection" "github.com/zeromicro/go-zero/core/trace" "github.com/zeromicro/go-zero/rest/internal/response" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/propagation" semconv "go.opentelemetry.io/otel/semconv/v1.4.0" oteltrace "go.opentelemetry.io/otel/trace" ) type ( // TraceOption defines the method to customize a traceOptions. TraceOption func(options *traceOptions) // traceOptions is TraceHandler options. traceOptions struct { traceIgnorePaths []string } ) // TraceHandler return a middleware that process the opentelemetry. func TraceHandler(serviceName, path string, opts ...TraceOption) func(http.Handler) http.Handler { var options traceOptions for _, opt := range opts { opt(&options) } ignorePaths := collection.NewSet[string]() ignorePaths.Add(options.traceIgnorePaths...) return func(next http.Handler) http.Handler { tracer := otel.Tracer(trace.TraceName) propagator := otel.GetTextMapPropagator() return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { spanName := path if len(spanName) == 0 { spanName = r.URL.Path } if ignorePaths.Contains(spanName) { next.ServeHTTP(w, r) return } ctx := propagator.Extract(r.Context(), propagation.HeaderCarrier(r.Header)) spanCtx, span := tracer.Start( ctx, spanName, oteltrace.WithSpanKind(oteltrace.SpanKindServer), oteltrace.WithAttributes(semconv.HTTPServerAttributesFromHTTPRequest( serviceName, spanName, r)...), ) defer span.End() // convenient for tracking error messages propagator.Inject(spanCtx, propagation.HeaderCarrier(w.Header())) trw := response.NewWithCodeResponseWriter(w) next.ServeHTTP(trw, r.WithContext(spanCtx)) span.SetAttributes(semconv.HTTPAttributesFromHTTPStatusCode(trw.Code)...) span.SetStatus(semconv.SpanStatusFromHTTPStatusCodeAndSpanKind( trw.Code, oteltrace.SpanKindServer)) }) } } // WithTraceIgnorePaths specifies the traceIgnorePaths option for TraceHandler. func WithTraceIgnorePaths(traceIgnorePaths []string) TraceOption { return func(options *traceOptions) { options.traceIgnorePaths = append(options.traceIgnorePaths, traceIgnorePaths...) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/metrichandler_test.go
rest/handler/metrichandler_test.go
package handler import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/stat" ) func TestMetricHandler(t *testing.T) { metrics := stat.NewMetrics("unit-test") metricHandler := MetricHandler(metrics) handler := metricHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/breakerhandler_test.go
rest/handler/breakerhandler_test.go
package handler import ( "fmt" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/stat" ) func init() { stat.SetReporter(nil) } func TestBreakerHandlerAccept(t *testing.T) { metrics := stat.NewMetrics("unit-test") breakerHandler := BreakerHandler(http.MethodGet, "/", metrics) handler := breakerHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Test", "test") _, err := w.Write([]byte("content")) assert.Nil(t, err) })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) req.Header.Set("X-Test", "test") resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) assert.Equal(t, "test", resp.Header().Get("X-Test")) assert.Equal(t, "content", resp.Body.String()) } func TestBreakerHandlerFail(t *testing.T) { metrics := stat.NewMetrics("unit-test") breakerHandler := BreakerHandler(http.MethodGet, "/", metrics) handler := breakerHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusBadGateway) })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusBadGateway, resp.Code) } func TestBreakerHandler_4XX(t *testing.T) { metrics := stat.NewMetrics("unit-test") breakerHandler := BreakerHandler(http.MethodGet, "/", metrics) handler := breakerHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusBadRequest) })) for i := 0; i < 1000; i++ { req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) } const tries = 100 var pass int for i := 0; i < tries; i++ { req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) if resp.Code == http.StatusBadRequest { pass++ } } assert.Equal(t, tries, pass) } func TestBreakerHandlerReject(t *testing.T) { metrics := stat.NewMetrics("unit-test") breakerHandler := BreakerHandler(http.MethodGet, "/", metrics) handler := breakerHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) })) for i := 0; i < 1000; i++ { req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) } var drops int for i := 0; i < 100; i++ { req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) if resp.Code == http.StatusServiceUnavailable { drops++ } } assert.True(t, drops >= 80, fmt.Sprintf("expected to be greater than 80, but got %d", drops)) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/sheddinghandler_test.go
rest/handler/sheddinghandler_test.go
package handler import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/load" "github.com/zeromicro/go-zero/core/stat" ) func TestSheddingHandlerAccept(t *testing.T) { metrics := stat.NewMetrics("unit-test") shedder := mockShedder{ allow: true, } sheddingHandler := SheddingHandler(shedder, metrics) handler := sheddingHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Test", "test") _, err := w.Write([]byte("content")) assert.Nil(t, err) })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) req.Header.Set("X-Test", "test") resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) assert.Equal(t, "test", resp.Header().Get("X-Test")) assert.Equal(t, "content", resp.Body.String()) } func TestSheddingHandlerFail(t *testing.T) { metrics := stat.NewMetrics("unit-test") shedder := mockShedder{ allow: true, } sheddingHandler := SheddingHandler(shedder, metrics) handler := sheddingHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusServiceUnavailable) })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusServiceUnavailable, resp.Code) } func TestSheddingHandlerReject(t *testing.T) { metrics := stat.NewMetrics("unit-test") shedder := mockShedder{ allow: false, } sheddingHandler := SheddingHandler(shedder, metrics) handler := sheddingHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusServiceUnavailable, resp.Code) } func TestSheddingHandlerNoShedding(t *testing.T) { metrics := stat.NewMetrics("unit-test") sheddingHandler := SheddingHandler(nil, metrics) handler := sheddingHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) } type mockShedder struct { allow bool } func (s mockShedder) Allow() (load.Promise, error) { if s.allow { return mockPromise{}, nil } return nil, load.ErrServiceOverloaded } type mockPromise struct{} func (p mockPromise) Pass() { } func (p mockPromise) Fail() { }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/timeouthandler.go
rest/handler/timeouthandler.go
package handler import ( "bufio" "bytes" "context" "errors" "fmt" "io" "net" "net/http" "path" "runtime" "strings" "sync" "time" "github.com/zeromicro/go-zero/rest/httpx" "github.com/zeromicro/go-zero/rest/internal" ) const ( statusClientClosedRequest = 499 reason = "Request Timeout" headerUpgrade = "Upgrade" valueWebsocket = "websocket" headerAccept = "Accept" valueSSE = "text/event-stream" ) // TimeoutHandler returns the handler with given timeout. // If client closed request, code 499 will be logged. // Notice: even if canceled in server side, 499 will be logged as well. func TimeoutHandler(duration time.Duration) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { if duration <= 0 { return next } return &timeoutHandler{ handler: next, dt: duration, } } } // timeoutHandler is the handler that controls the request timeout. // Why we implement it on our own, because the stdlib implementation // treats the ClientClosedRequest as http.StatusServiceUnavailable. // And we write the codes in logs as code 499, which is defined by nginx. type timeoutHandler struct { handler http.Handler dt time.Duration } func (h *timeoutHandler) errorBody() string { return reason } func (h *timeoutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.Header.Get(headerUpgrade) == valueWebsocket || // Server-Sent Event ignore timeout. r.Header.Get(headerAccept) == valueSSE { h.handler.ServeHTTP(w, r) return } ctx, cancelCtx := context.WithTimeout(r.Context(), h.dt) defer cancelCtx() r = r.WithContext(ctx) done := make(chan struct{}) tw := &timeoutWriter{ w: w, h: make(http.Header), req: r, code: http.StatusOK, } panicChan := make(chan any, 1) go func() { defer func() { if p := recover(); p != nil { panicChan <- p } }() h.handler.ServeHTTP(tw, r) close(done) }() select { case p := <-panicChan: panic(p) case <-done: tw.mu.Lock() defer tw.mu.Unlock() dst := w.Header() for k, vv := range tw.h { dst[k] = vv } // We don't need to write header 200, because it's written by default. // If we write it again, it will cause a warning: `http: superfluous response.WriteHeader call`. if tw.code != http.StatusOK { w.WriteHeader(tw.code) } w.Write(tw.wbuf.Bytes()) case <-ctx.Done(): tw.mu.Lock() defer tw.mu.Unlock() // there isn't any user-defined middleware before TimeoutHandler, // so we can guarantee that cancellation in biz related code won't come here. httpx.ErrorCtx(r.Context(), w, ctx.Err(), func(w http.ResponseWriter, err error) { if errors.Is(err, context.Canceled) { w.WriteHeader(statusClientClosedRequest) } else { w.WriteHeader(http.StatusServiceUnavailable) } _, _ = io.WriteString(w, h.errorBody()) }) tw.timedOut = true } } type timeoutWriter struct { w http.ResponseWriter h http.Header wbuf bytes.Buffer req *http.Request mu sync.Mutex timedOut bool wroteHeader bool code int } var _ http.Pusher = (*timeoutWriter)(nil) // Flush implements the Flusher interface. func (tw *timeoutWriter) Flush() { flusher, ok := tw.w.(http.Flusher) if !ok { return } header := tw.w.Header() for k, v := range tw.h { header[k] = v } tw.w.Write(tw.wbuf.Bytes()) tw.wbuf.Reset() flusher.Flush() } // Header returns the underlying temporary http.Header. func (tw *timeoutWriter) Header() http.Header { return tw.h } // Hijack implements the Hijacker interface. func (tw *timeoutWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { if hijacked, ok := tw.w.(http.Hijacker); ok { return hijacked.Hijack() } return nil, nil, errors.New("server doesn't support hijacking") } // Push implements the Pusher interface. func (tw *timeoutWriter) Push(target string, opts *http.PushOptions) error { if pusher, ok := tw.w.(http.Pusher); ok { return pusher.Push(target, opts) } return http.ErrNotSupported } // Write writes the data to the connection as part of an HTTP reply. // Timeout and multiple header written are guarded. func (tw *timeoutWriter) Write(p []byte) (int, error) { tw.mu.Lock() defer tw.mu.Unlock() if tw.timedOut { return 0, http.ErrHandlerTimeout } if !tw.wroteHeader { tw.writeHeaderLocked(http.StatusOK) } return tw.wbuf.Write(p) } func (tw *timeoutWriter) WriteHeader(code int) { tw.mu.Lock() defer tw.mu.Unlock() if !tw.wroteHeader { tw.writeHeaderLocked(code) } } func (tw *timeoutWriter) writeHeaderLocked(code int) { checkWriteHeaderCode(code) switch { case tw.timedOut: return case tw.wroteHeader: if tw.req != nil { caller := relevantCaller() internal.Errorf(tw.req, "http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line) } default: tw.wroteHeader = true tw.code = code } } func checkWriteHeaderCode(code int) { if code < 100 || code > 599 { panic(fmt.Sprintf("invalid WriteHeader code %v", code)) } } // relevantCaller searches the call stack for the first function outside of net/http. // The purpose of this function is to provide more helpful error messages. func relevantCaller() runtime.Frame { pc := make([]uintptr, 16) n := runtime.Callers(1, pc) frames := runtime.CallersFrames(pc[:n]) var frame runtime.Frame for { frame, more := frames.Next() if !strings.HasPrefix(frame.Function, "net/http.") { return frame } if !more { break } } return frame }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/loghandler_test.go
rest/handler/loghandler_test.go
package handler import ( "bytes" "errors" "io" "net/http" "net/http/httptest" "testing" "time" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/logx/logtest" "github.com/zeromicro/go-zero/rest/internal" "github.com/zeromicro/go-zero/rest/internal/response" ) func TestLogHandler(t *testing.T) { handlers := []func(handler http.Handler) http.Handler{ LogHandler, DetailedLogHandler, } for _, logHandler := range handlers { req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) handler := logHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { internal.LogCollectorFromContext(r.Context()).Append("anything") w.Header().Set("X-Test", "test") w.WriteHeader(http.StatusServiceUnavailable) _, err := w.Write([]byte("content")) assert.Nil(t, err) flusher, ok := w.(http.Flusher) assert.True(t, ok) flusher.Flush() })) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusServiceUnavailable, resp.Code) assert.Equal(t, "test", resp.Header().Get("X-Test")) assert.Equal(t, "content", resp.Body.String()) } } func TestLogHandlerVeryLong(t *testing.T) { var buf bytes.Buffer for i := 0; i < limitBodyBytes<<1; i++ { buf.WriteByte('a') } req := httptest.NewRequest(http.MethodPost, "http://localhost", &buf) handler := LogHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { internal.LogCollectorFromContext(r.Context()).Append("anything") _, _ = io.Copy(io.Discard, r.Body) w.Header().Set("X-Test", "test") w.WriteHeader(http.StatusServiceUnavailable) _, err := w.Write([]byte("content")) assert.Nil(t, err) flusher, ok := w.(http.Flusher) assert.True(t, ok) flusher.Flush() })) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusServiceUnavailable, resp.Code) assert.Equal(t, "test", resp.Header().Get("X-Test")) assert.Equal(t, "content", resp.Body.String()) } func TestLogHandlerSlow(t *testing.T) { handlers := []func(handler http.Handler) http.Handler{ LogHandler, DetailedLogHandler, } for _, logHandler := range handlers { req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) handler := logHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(defaultSlowThreshold + time.Millisecond*50) })) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) } } func TestLogHandlerSSE(t *testing.T) { handlers := []func(handler http.Handler) http.Handler{ LogHandler, DetailedLogHandler, } for _, logHandler := range handlers { t.Run("SSE request with normal duration", func(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) req.Header.Set(headerAccept, valueSSE) handler := logHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(defaultSlowThreshold + time.Second) w.WriteHeader(http.StatusOK) })) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) }) t.Run("SSE request exceeding SSE threshold", func(t *testing.T) { originalThreshold := sseSlowThreshold.Load() SetSSESlowThreshold(time.Millisecond * 100) defer SetSSESlowThreshold(originalThreshold) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) req.Header.Set(headerAccept, valueSSE) handler := logHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(time.Millisecond * 150) w.WriteHeader(http.StatusOK) })) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) }) } } func TestLogHandlerThresholdSelection(t *testing.T) { tests := []struct { name string acceptHeader string expectedIsSSE bool }{ { name: "Regular HTTP request", acceptHeader: "text/html", expectedIsSSE: false, }, { name: "SSE request", acceptHeader: valueSSE, expectedIsSSE: true, }, { name: "No Accept header", acceptHeader: "", expectedIsSSE: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) if tt.acceptHeader != "" { req.Header.Set(headerAccept, tt.acceptHeader) } SetSlowThreshold(time.Millisecond * 100) SetSSESlowThreshold(time.Millisecond * 200) defer func() { SetSlowThreshold(defaultSlowThreshold) SetSSESlowThreshold(defaultSSESlowThreshold) }() handler := LogHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(time.Millisecond * 150) w.WriteHeader(http.StatusOK) })) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) }) } } func TestDetailedLogHandler_LargeBody(t *testing.T) { lbuf := logtest.NewCollector(t) var buf bytes.Buffer for i := 0; i < limitDetailedBodyBytes<<2; i++ { buf.WriteByte('a') } req := httptest.NewRequest(http.MethodPost, "http://localhost", &buf) h := DetailedLogHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.Copy(io.Discard, r.Body) })) resp := httptest.NewRecorder() h.ServeHTTP(resp, req) // extra 200 for the length of POST request headers assert.True(t, len(lbuf.Content()) < limitDetailedBodyBytes+200) } func TestDetailedLogHandler_Hijack(t *testing.T) { resp := httptest.NewRecorder() writer := &detailLoggedResponseWriter{ writer: response.NewWithCodeResponseWriter(resp), } assert.NotPanics(t, func() { _, _, _ = writer.Hijack() }) writer = &detailLoggedResponseWriter{ writer: response.NewWithCodeResponseWriter(resp), } assert.NotPanics(t, func() { _, _, _ = writer.Hijack() }) writer = &detailLoggedResponseWriter{ writer: response.NewWithCodeResponseWriter(mockedHijackable{ ResponseRecorder: resp, }), } assert.NotPanics(t, func() { _, _, _ = writer.Hijack() }) } func TestSetSlowThreshold(t *testing.T) { assert.Equal(t, defaultSlowThreshold, slowThreshold.Load()) SetSlowThreshold(time.Second) assert.Equal(t, time.Second, slowThreshold.Load()) } func TestSetSSESlowThreshold(t *testing.T) { assert.Equal(t, defaultSSESlowThreshold, sseSlowThreshold.Load()) SetSSESlowThreshold(time.Minute * 10) assert.Equal(t, time.Minute*10, sseSlowThreshold.Load()) } func TestWrapMethodWithColor(t *testing.T) { // no tty assert.Equal(t, http.MethodGet, wrapMethod(http.MethodGet)) assert.Equal(t, http.MethodPost, wrapMethod(http.MethodPost)) assert.Equal(t, http.MethodPut, wrapMethod(http.MethodPut)) assert.Equal(t, http.MethodDelete, wrapMethod(http.MethodDelete)) assert.Equal(t, http.MethodPatch, wrapMethod(http.MethodPatch)) assert.Equal(t, http.MethodHead, wrapMethod(http.MethodHead)) assert.Equal(t, http.MethodOptions, wrapMethod(http.MethodOptions)) assert.Equal(t, http.MethodConnect, wrapMethod(http.MethodConnect)) assert.Equal(t, http.MethodTrace, wrapMethod(http.MethodTrace)) } func TestWrapStatusCodeWithColor(t *testing.T) { // no tty assert.Equal(t, "200", wrapStatusCode(http.StatusOK)) assert.Equal(t, "302", wrapStatusCode(http.StatusFound)) assert.Equal(t, "404", wrapStatusCode(http.StatusNotFound)) assert.Equal(t, "500", wrapStatusCode(http.StatusInternalServerError)) assert.Equal(t, "503", wrapStatusCode(http.StatusServiceUnavailable)) } func TestDumpRequest(t *testing.T) { const errMsg = "error" r := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) r.Body = mockedReadCloser{errMsg: errMsg} assert.Equal(t, errMsg, dumpRequest(r)) } func BenchmarkLogHandler(b *testing.B) { b.ReportAllocs() req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) handler := LogHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) for i := 0; i < b.N; i++ { resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) } } type mockedReadCloser struct { errMsg string } func (m mockedReadCloser) Read(_ []byte) (n int, err error) { return 0, errors.New(m.errMsg) } func (m mockedReadCloser) Close() error { return nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/tracehandler_test.go
rest/handler/tracehandler_test.go
package handler import ( "context" "io" "net/http" "net/http/httptest" "strconv" "testing" "github.com/stretchr/testify/assert" ztrace "github.com/zeromicro/go-zero/core/trace" "github.com/zeromicro/go-zero/core/trace/tracetest" "github.com/zeromicro/go-zero/rest/chain" "go.opentelemetry.io/otel" tcodes "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/propagation" sdktrace "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/trace" ) func TestOtelHandler(t *testing.T) { ztrace.StartAgent(ztrace.Config{ Name: "go-zero-test", Endpoint: "http://localhost:14268", OtlpHttpPath: "/v1/traces", Batcher: "otlphttp", Sampler: 1.0, }) defer ztrace.StopAgent() for _, test := range []string{"", "bar"} { t.Run(test, func(t *testing.T) { h := chain.New(TraceHandler("foo", test)).Then( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { span := trace.SpanFromContext(r.Context()) assert.True(t, span.SpanContext().IsValid()) assert.True(t, span.IsRecording()) })) ts := httptest.NewServer(h) defer ts.Close() client := ts.Client() err := func(ctx context.Context) error { ctx, span := otel.Tracer("httptrace/client").Start(ctx, "test") defer span.End() req, _ := http.NewRequest("GET", ts.URL, nil) otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(req.Header)) res, err := client.Do(req) assert.Nil(t, err) return res.Body.Close() }(context.Background()) assert.Nil(t, err) }) } } func TestTraceHandler(t *testing.T) { me := tracetest.NewInMemoryExporter(t) h := chain.New(TraceHandler("foo", "/")).Then( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) ts := httptest.NewServer(h) defer ts.Close() client := ts.Client() err := func(ctx context.Context) error { req, _ := http.NewRequest("GET", ts.URL, nil) res, err := client.Do(req) assert.Nil(t, err) return res.Body.Close() }(context.Background()) assert.NoError(t, err) assert.Equal(t, 1, len(me.GetSpans())) span := me.GetSpans()[0].Snapshot() assert.Equal(t, sdktrace.Status{ Code: tcodes.Unset, }, span.Status()) assert.Equal(t, 0, len(span.Events())) assert.Equal(t, 9, len(span.Attributes())) } func TestDontTracingSpan(t *testing.T) { ztrace.StartAgent(ztrace.Config{ Name: "go-zero-test", Endpoint: "http://localhost:14268", OtlpHttpPath: "/v1/traces", Batcher: "otlphttp", Sampler: 1.0, }) defer ztrace.StopAgent() for _, test := range []string{"", "bar", "foo"} { t.Run(test, func(t *testing.T) { h := chain.New(TraceHandler("foo", test, WithTraceIgnorePaths([]string{"bar"}))).Then( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { span := trace.SpanFromContext(r.Context()) spanCtx := span.SpanContext() if test == "bar" { assert.False(t, spanCtx.IsValid()) assert.False(t, span.IsRecording()) return } assert.True(t, span.IsRecording()) assert.True(t, spanCtx.IsValid()) })) ts := httptest.NewServer(h) defer ts.Close() client := ts.Client() err := func(ctx context.Context) error { ctx, span := otel.Tracer("httptrace/client").Start(ctx, "test") defer span.End() req, _ := http.NewRequest("GET", ts.URL, nil) otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(req.Header)) res, err := client.Do(req) assert.Nil(t, err) return res.Body.Close() }(context.Background()) assert.Nil(t, err) }) } } func TestTraceResponseWriter(t *testing.T) { ztrace.StartAgent(ztrace.Config{ Name: "go-zero-test", Endpoint: "http://localhost:14268", OtlpHttpPath: "/v1/traces", Batcher: "otlphttp", Sampler: 1.0, }) defer ztrace.StopAgent() for _, test := range []int{0, 200, 300, 400, 401, 500, 503} { t.Run(strconv.Itoa(test), func(t *testing.T) { h := chain.New(TraceHandler("foo", "bar")).Then( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { span := trace.SpanFromContext(r.Context()) spanCtx := span.SpanContext() assert.True(t, span.IsRecording()) assert.True(t, spanCtx.IsValid()) if test != 0 { w.WriteHeader(test) } w.Write([]byte("hello")) })) ts := httptest.NewServer(h) defer ts.Close() client := ts.Client() err := func(ctx context.Context) error { ctx, span := otel.Tracer("httptrace/client").Start(ctx, "test") defer span.End() req, _ := http.NewRequest("GET", ts.URL, nil) otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(req.Header)) res, err := client.Do(req) assert.Nil(t, err) resBody := make([]byte, 5) _, err = res.Body.Read(resBody) assert.Equal(t, io.EOF, err) assert.Equal(t, []byte("hello"), resBody, "response body fail") return res.Body.Close() }(context.Background()) assert.Nil(t, err) }) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/gunziphandler.go
rest/handler/gunziphandler.go
package handler import ( "compress/gzip" "net/http" "strings" "github.com/zeromicro/go-zero/rest/httpx" ) const gzipEncoding = "gzip" // GunzipHandler returns a middleware to gunzip http request body. func GunzipHandler(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if strings.Contains(r.Header.Get(httpx.ContentEncoding), gzipEncoding) { reader, err := gzip.NewReader(r.Body) if err != nil { w.WriteHeader(http.StatusBadRequest) return } r.Body = reader } next.ServeHTTP(w, r) }) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/gunziphandler_test.go
rest/handler/gunziphandler_test.go
package handler import ( "bytes" "io" "net/http" "net/http/httptest" "strings" "sync" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/codec" "github.com/zeromicro/go-zero/rest/httpx" ) func TestGunzipHandler(t *testing.T) { const message = "hello world" var wg sync.WaitGroup wg.Add(1) handler := GunzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(r.Body) assert.Nil(t, err) assert.Equal(t, string(body), message) wg.Done() })) req := httptest.NewRequest(http.MethodPost, "http://localhost", bytes.NewReader(codec.Gzip([]byte(message)))) req.Header.Set(httpx.ContentEncoding, gzipEncoding) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) wg.Wait() } func TestGunzipHandler_NoGzip(t *testing.T) { const message = "hello world" var wg sync.WaitGroup wg.Add(1) handler := GunzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(r.Body) assert.Nil(t, err) assert.Equal(t, string(body), message) wg.Done() })) req := httptest.NewRequest(http.MethodPost, "http://localhost", strings.NewReader(message)) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) wg.Wait() } func TestGunzipHandler_NoGzipButTelling(t *testing.T) { const message = "hello world" handler := GunzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) req := httptest.NewRequest(http.MethodPost, "http://localhost", strings.NewReader(message)) req.Header.Set(httpx.ContentEncoding, gzipEncoding) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusBadRequest, resp.Code) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/metrichandler.go
rest/handler/metrichandler.go
package handler import ( "net/http" "github.com/zeromicro/go-zero/core/stat" "github.com/zeromicro/go-zero/core/timex" ) // MetricHandler returns a middleware that stat the metrics. func MetricHandler(metrics *stat.Metrics) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { startTime := timex.Now() defer func() { metrics.Add(stat.Task{ Duration: timex.Since(startTime), }) }() next.ServeHTTP(w, r) }) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/authhandler_test.go
rest/handler/authhandler_test.go
package handler import ( "bufio" "net" "net/http" "net/http/httptest" "testing" "time" "github.com/golang-jwt/jwt/v4" "github.com/stretchr/testify/assert" ) func TestAuthHandlerFailed(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) handler := Authorize("B63F477D-BBA3-4E52-96D3-C0034C27694A", WithUnauthorizedCallback( func(w http.ResponseWriter, r *http.Request, err error) { assert.NotNil(t, err) w.Header().Set("X-Test", err.Error()) w.WriteHeader(http.StatusUnauthorized) _, err = w.Write([]byte("content")) assert.Nil(t, err) }))( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusUnauthorized, resp.Code) } func TestAuthHandler(t *testing.T) { const key = "B63F477D-BBA3-4E52-96D3-C0034C27694A" req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) token, err := buildToken(key, map[string]any{ "key": "value", }, 3600) assert.Nil(t, err) req.Header.Set("Authorization", "Bearer "+token) handler := Authorize(key)( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Test", "test") _, err := w.Write([]byte("content")) assert.Nil(t, err) flusher, ok := w.(http.Flusher) assert.True(t, ok) flusher.Flush() })) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) assert.Equal(t, "test", resp.Header().Get("X-Test")) assert.Equal(t, "content", resp.Body.String()) } func TestAuthHandlerWithPrevSecret(t *testing.T) { const ( key = "14F17379-EB8F-411B-8F12-6929002DCA76" prevKey = "B63F477D-BBA3-4E52-96D3-C0034C27694A" ) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) token, err := buildToken(key, map[string]any{ "key": "value", }, 3600) assert.Nil(t, err) req.Header.Set("Authorization", "Bearer "+token) handler := Authorize(key, WithPrevSecret(prevKey))( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Test", "test") _, err := w.Write([]byte("content")) assert.Nil(t, err) })) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) assert.Equal(t, "test", resp.Header().Get("X-Test")) assert.Equal(t, "content", resp.Body.String()) } func TestAuthHandler_NilError(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() assert.NotPanics(t, func() { unauthorized(resp, req, nil, nil) }) } func buildToken(secretKey string, payloads map[string]any, seconds int64) (string, error) { now := time.Now().Unix() claims := make(jwt.MapClaims) claims["exp"] = now + seconds claims["iat"] = now for k, v := range payloads { claims[k] = v } token := jwt.New(jwt.SigningMethodHS256) token.Claims = claims return token.SignedString([]byte(secretKey)) } type mockedHijackable struct { *httptest.ResponseRecorder } func (m mockedHijackable) Hijack() (net.Conn, *bufio.ReadWriter, error) { return nil, nil, nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/cryptionhandler.go
rest/handler/cryptionhandler.go
package handler import ( "bufio" "bytes" "context" "encoding/base64" "errors" "io" "net" "net/http" "github.com/zeromicro/go-zero/core/codec" "github.com/zeromicro/go-zero/core/logc" ) const maxBytes = 1 << 20 // 1 MiB var errContentLengthExceeded = errors.New("content length exceeded") // CryptionHandler returns a middleware to handle cryption. func CryptionHandler(key []byte) func(http.Handler) http.Handler { return LimitCryptionHandler(maxBytes, key) } // LimitCryptionHandler returns a middleware to handle cryption. func LimitCryptionHandler(limitBytes int64, key []byte) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { cw := newCryptionResponseWriter(w) defer cw.flush(r.Context(), key) if r.ContentLength <= 0 { next.ServeHTTP(cw, r) return } if err := decryptBody(limitBytes, key, r); err != nil { w.WriteHeader(http.StatusBadRequest) return } next.ServeHTTP(cw, r) }) } } func decryptBody(limitBytes int64, key []byte, r *http.Request) error { if limitBytes > 0 && r.ContentLength > limitBytes { return errContentLengthExceeded } var content []byte var err error if r.ContentLength > 0 { content = make([]byte, r.ContentLength) _, err = io.ReadFull(r.Body, content) } else { content, err = io.ReadAll(io.LimitReader(r.Body, maxBytes)) } if err != nil { return err } content, err = base64.StdEncoding.DecodeString(string(content)) if err != nil { return err } output, err := codec.EcbDecrypt(key, content) if err != nil { return err } var buf bytes.Buffer buf.Write(output) r.Body = io.NopCloser(&buf) return nil } type cryptionResponseWriter struct { http.ResponseWriter buf *bytes.Buffer } func newCryptionResponseWriter(w http.ResponseWriter) *cryptionResponseWriter { return &cryptionResponseWriter{ ResponseWriter: w, buf: new(bytes.Buffer), } } func (w *cryptionResponseWriter) Flush() { if flusher, ok := w.ResponseWriter.(http.Flusher); ok { flusher.Flush() } } func (w *cryptionResponseWriter) Header() http.Header { return w.ResponseWriter.Header() } // Hijack implements the http.Hijacker interface. // This expands the Response to fulfill http.Hijacker if the underlying http.ResponseWriter supports it. func (w *cryptionResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { if hijacked, ok := w.ResponseWriter.(http.Hijacker); ok { return hijacked.Hijack() } return nil, nil, errors.New("server doesn't support hijacking") } func (w *cryptionResponseWriter) Write(p []byte) (int, error) { return w.buf.Write(p) } func (w *cryptionResponseWriter) WriteHeader(statusCode int) { w.ResponseWriter.WriteHeader(statusCode) } func (w *cryptionResponseWriter) flush(ctx context.Context, key []byte) { if w.buf.Len() == 0 { return } content, err := codec.EcbEncrypt(key, w.buf.Bytes()) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } body := base64.StdEncoding.EncodeToString(content) if n, err := io.WriteString(w.ResponseWriter, body); err != nil { logc.Errorf(ctx, "write response failed, error: %s", err) } else if n < len(body) { logc.Errorf(ctx, "actual bytes: %d, written bytes: %d", len(body), n) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/recoverhandler.go
rest/handler/recoverhandler.go
package handler import ( "fmt" "net/http" "runtime/debug" "github.com/zeromicro/go-zero/rest/internal" ) // RecoverHandler returns a middleware that recovers if panic happens. func RecoverHandler(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer func() { if result := recover(); result != nil { internal.Error(r, fmt.Sprintf("%v\n%s", result, debug.Stack())) w.WriteHeader(http.StatusInternalServerError) } }() next.ServeHTTP(w, r) }) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/cryptionhandler_test.go
rest/handler/cryptionhandler_test.go
package handler import ( "bytes" "context" "crypto/rand" "encoding/base64" "io" "net/http" "net/http/httptest" "strings" "testing" "testing/iotest" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/codec" "github.com/zeromicro/go-zero/core/logx/logtest" ) const ( reqText = "ping" respText = "pong" ) var aesKey = []byte(`PdSgVkYp3s6v9y$B&E)H+MbQeThWmZq4`) func TestCryptionHandlerGet(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/any", http.NoBody) handler := CryptionHandler(aesKey)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, err := w.Write([]byte(respText)) w.Header().Set("X-Test", "test") assert.Nil(t, err) })) recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, req) expect, err := codec.EcbEncrypt(aesKey, []byte(respText)) assert.Nil(t, err) assert.Equal(t, http.StatusOK, recorder.Code) assert.Equal(t, "test", recorder.Header().Get("X-Test")) assert.Equal(t, base64.StdEncoding.EncodeToString(expect), recorder.Body.String()) } func TestCryptionHandlerGet_badKey(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/any", http.NoBody) handler := CryptionHandler(append(aesKey, aesKey...))(http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { _, err := w.Write([]byte(respText)) w.Header().Set("X-Test", "test") assert.Nil(t, err) })) recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, req) assert.Equal(t, http.StatusInternalServerError, recorder.Code) } func TestCryptionHandlerPost(t *testing.T) { var buf bytes.Buffer enc, err := codec.EcbEncrypt(aesKey, []byte(reqText)) assert.Nil(t, err) buf.WriteString(base64.StdEncoding.EncodeToString(enc)) req := httptest.NewRequest(http.MethodPost, "/any", &buf) handler := CryptionHandler(aesKey)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(r.Body) assert.Nil(t, err) assert.Equal(t, reqText, string(body)) w.Write([]byte(respText)) })) recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, req) expect, err := codec.EcbEncrypt(aesKey, []byte(respText)) assert.Nil(t, err) assert.Equal(t, http.StatusOK, recorder.Code) assert.Equal(t, base64.StdEncoding.EncodeToString(expect), recorder.Body.String()) } func TestCryptionHandlerPostBadEncryption(t *testing.T) { var buf bytes.Buffer enc, err := codec.EcbEncrypt(aesKey, []byte(reqText)) assert.Nil(t, err) buf.Write(enc) req := httptest.NewRequest(http.MethodPost, "/any", &buf) handler := CryptionHandler(aesKey)(nil) recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, req) assert.Equal(t, http.StatusBadRequest, recorder.Code) } func TestCryptionHandlerWriteHeader(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/any", http.NoBody) handler := CryptionHandler(aesKey)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusServiceUnavailable) })) recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, req) assert.Equal(t, http.StatusServiceUnavailable, recorder.Code) } func TestCryptionHandlerFlush(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/any", http.NoBody) handler := CryptionHandler(aesKey)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(respText)) flusher, ok := w.(http.Flusher) assert.True(t, ok) flusher.Flush() })) recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, req) expect, err := codec.EcbEncrypt(aesKey, []byte(respText)) assert.Nil(t, err) assert.Equal(t, base64.StdEncoding.EncodeToString(expect), recorder.Body.String()) } func TestCryptionHandler_Hijack(t *testing.T) { resp := httptest.NewRecorder() writer := newCryptionResponseWriter(resp) assert.NotPanics(t, func() { writer.Hijack() }) writer = newCryptionResponseWriter(mockedHijackable{resp}) assert.NotPanics(t, func() { 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) _, err := rand.Read(body) assert.NoError(t, err) 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) } func TestCryptionHandler_BadBody(t *testing.T) { req, err := http.NewRequest(http.MethodPost, "/foo", iotest.ErrReader(io.ErrUnexpectedEOF)) assert.Nil(t, err) err = decryptBody(maxBytes, aesKey, req) assert.ErrorIs(t, err, io.ErrUnexpectedEOF) } func TestCryptionHandler_BadKey(t *testing.T) { var buf bytes.Buffer enc, err := codec.EcbEncrypt(aesKey, []byte(reqText)) assert.Nil(t, err) buf.WriteString(base64.StdEncoding.EncodeToString(enc)) req := httptest.NewRequest(http.MethodPost, "/any", &buf) err = decryptBody(maxBytes, append(aesKey, aesKey...), req) assert.Error(t, err) } func TestCryptionResponseWriter_Flush(t *testing.T) { body := []byte("hello, world!") t.Run("half", func(t *testing.T) { recorder := httptest.NewRecorder() f := flushableResponseWriter{ writer: &halfWriter{recorder}, } w := newCryptionResponseWriter(f) _, err := w.Write(body) assert.NoError(t, err) w.flush(context.Background(), aesKey) b, err := io.ReadAll(recorder.Body) assert.NoError(t, err) expected, err := codec.EcbEncrypt(aesKey, body) assert.NoError(t, err) assert.True(t, strings.HasPrefix(base64.StdEncoding.EncodeToString(expected), string(b))) assert.True(t, len(string(b)) < len(base64.StdEncoding.EncodeToString(expected))) }) t.Run("full", func(t *testing.T) { recorder := httptest.NewRecorder() f := flushableResponseWriter{ writer: recorder, } w := newCryptionResponseWriter(f) _, err := w.Write(body) assert.NoError(t, err) w.flush(context.Background(), aesKey) b, err := io.ReadAll(recorder.Body) assert.NoError(t, err) expected, err := codec.EcbEncrypt(aesKey, body) assert.NoError(t, err) assert.Equal(t, base64.StdEncoding.EncodeToString(expected), string(b)) }) t.Run("bad writer", func(t *testing.T) { buf := logtest.NewCollector(t) f := flushableResponseWriter{ writer: new(badWriter), } w := newCryptionResponseWriter(f) _, err := w.Write(body) assert.NoError(t, err) w.flush(context.Background(), aesKey) assert.True(t, strings.Contains(buf.Content(), io.ErrClosedPipe.Error())) }) } type flushableResponseWriter struct { writer io.Writer } func (m flushableResponseWriter) Header() http.Header { panic("implement me") } func (m flushableResponseWriter) Write(p []byte) (int, error) { return m.writer.Write(p) } func (m flushableResponseWriter) WriteHeader(_ int) { panic("implement me") } type halfWriter struct { w io.Writer } func (t *halfWriter) Write(p []byte) (n int, err error) { n = len(p) >> 1 return t.w.Write(p[0:n]) } type badWriter struct { } func (b *badWriter) Write(_ []byte) (n int, err error) { return 0, io.ErrClosedPipe }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/maxbyteshandler_test.go
rest/handler/maxbyteshandler_test.go
package handler import ( "bytes" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestMaxBytesHandler(t *testing.T) { maxb := MaxBytesHandler(10) handler := maxb(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) req := httptest.NewRequest(http.MethodPost, "http://localhost", bytes.NewBufferString("123456789012345")) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusRequestEntityTooLarge, resp.Code) req = httptest.NewRequest(http.MethodPost, "http://localhost", bytes.NewBufferString("12345")) resp = httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) } func TestMaxBytesHandlerNoLimit(t *testing.T) { maxb := MaxBytesHandler(-1) handler := maxb(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) req := httptest.NewRequest(http.MethodPost, "http://localhost", bytes.NewBufferString("123456789012345")) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/timeouthandler_test.go
rest/handler/timeouthandler_test.go
package handler import ( "bufio" "context" "fmt" "net/http" "net/http/httptest" "strconv" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/logx/logtest" "github.com/zeromicro/go-zero/rest/internal/response" ) func TestTimeoutWriteFlushOutput(t *testing.T) { t.Run("flusher", func(t *testing.T) { timeoutHandler := TimeoutHandler(1000 * time.Millisecond) handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/event-stream; charset=utf-8") flusher, ok := w.(http.Flusher) if !ok { http.Error(w, "Flushing not supported", http.StatusInternalServerError) return } for i := 1; i <= 5; i++ { fmt.Fprint(w, strconv.Itoa(i)+" cats\n\n") flusher.Flush() time.Sleep(time.Millisecond) } })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) scanner := bufio.NewScanner(resp.Body) var cats int for scanner.Scan() { line := scanner.Text() if strings.Contains(line, "cats") { cats++ } } if err := scanner.Err(); err != nil { cats = 0 } assert.Equal(t, 5, cats) }) t.Run("writer", func(t *testing.T) { recorder := httptest.NewRecorder() timeoutHandler := TimeoutHandler(1000 * time.Millisecond) handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/event-stream; charset=utf-8") flusher, ok := w.(http.Flusher) if !ok { http.Error(w, "Flushing not supported", http.StatusInternalServerError) return } for i := 1; i <= 5; i++ { fmt.Fprint(w, strconv.Itoa(i)+" cats\n\n") flusher.Flush() time.Sleep(time.Millisecond) assert.Empty(t, recorder.Body.String()) } })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := mockedResponseWriter{recorder} handler.ServeHTTP(resp, req) assert.Equal(t, "1 cats\n\n2 cats\n\n3 cats\n\n4 cats\n\n5 cats\n\n", recorder.Body.String()) }) } func TestTimeout(t *testing.T) { timeoutHandler := TimeoutHandler(time.Millisecond) handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(time.Minute) })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusServiceUnavailable, resp.Code) } func TestWithinTimeout(t *testing.T) { timeoutHandler := TimeoutHandler(time.Second) handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(time.Millisecond) })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) } func TestWithinTimeoutBadCode(t *testing.T) { timeoutHandler := TimeoutHandler(time.Second) handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusInternalServerError, resp.Code) } func TestWithTimeoutTimedout(t *testing.T) { timeoutHandler := TimeoutHandler(time.Millisecond) handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(time.Millisecond * 10) _, err := w.Write([]byte(`foo`)) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusServiceUnavailable, resp.Code) } func TestWithoutTimeout(t *testing.T) { timeoutHandler := TimeoutHandler(0) handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(100 * time.Millisecond) })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) } func TestTimeoutPanic(t *testing.T) { timeoutHandler := TimeoutHandler(time.Minute) handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { panic("foo") })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() assert.Panics(t, func() { handler.ServeHTTP(resp, req) }) } func TestTimeoutSSE(t *testing.T) { timeoutHandler := TimeoutHandler(time.Millisecond) handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(time.Millisecond * 10) r.Header.Set("Content-Type", "text/event-stream") r.Header.Set("Cache-Control", "no-cache") r.Header.Set("Connection", "keep-alive") r.Header.Set("Transfer-Encoding", "chunked") })) req := httptest.NewRequest(http.MethodGet, "http://localhost", nil) req.Header.Set(headerAccept, valueSSE) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) } 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", http.NoBody) 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) { _, err := w.Write([]byte(`hello`)) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } w.Header().Set("foo", "bar") w.WriteHeader(http.StatusOK) })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) } func TestTimeoutWriteBadCode(t *testing.T) { timeoutHandler := TimeoutHandler(time.Minute) handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(1000) })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() assert.Panics(t, func() { handler.ServeHTTP(resp, req) }) } func TestTimeoutClientClosed(t *testing.T) { timeoutHandler := TimeoutHandler(time.Minute) handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusServiceUnavailable) })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) ctx, cancel := context.WithCancel(context.Background()) req = req.WithContext(ctx) cancel() resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, statusClientClosedRequest, resp.Code) } func TestTimeoutHijack(t *testing.T) { resp := httptest.NewRecorder() writer := &timeoutWriter{ w: response.NewWithCodeResponseWriter(resp), } assert.NotPanics(t, func() { _, _, _ = writer.Hijack() }) writer = &timeoutWriter{ w: response.NewWithCodeResponseWriter(mockedHijackable{resp}), } assert.NotPanics(t, func() { _, _, _ = writer.Hijack() }) } func TestTimeoutFlush(t *testing.T) { timeoutHandler := TimeoutHandler(time.Minute) handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { flusher, ok := w.(http.Flusher) if !ok { http.Error(w, "Streaming unsupported!", http.StatusInternalServerError) return } flusher.Flush() })) req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody) resp := httptest.NewRecorder() handler.ServeHTTP(resp, req) assert.Equal(t, http.StatusOK, resp.Code) } func TestTimeoutPusher(t *testing.T) { handler := &timeoutWriter{ w: mockedPusher{}, } assert.Panics(t, func() { _ = handler.Push("any", nil) }) handler = &timeoutWriter{ w: httptest.NewRecorder(), } assert.Equal(t, http.ErrNotSupported, handler.Push("any", nil)) } func TestTimeoutWriter_Hijack(t *testing.T) { writer := &timeoutWriter{ w: httptest.NewRecorder(), h: make(http.Header), req: httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody), } _, _, err := writer.Hijack() assert.Error(t, err) } func TestTimeoutWroteTwice(t *testing.T) { c := logtest.NewCollector(t) writer := &timeoutWriter{ w: response.NewWithCodeResponseWriter(httptest.NewRecorder()), h: make(http.Header), req: httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody), } writer.writeHeaderLocked(http.StatusOK) writer.writeHeaderLocked(http.StatusOK) assert.Contains(t, c.String(), "superfluous response.WriteHeader call") } type mockedPusher struct{} func (m mockedPusher) Header() http.Header { panic("implement me") } func (m mockedPusher) Write(_ []byte) (int, error) { panic("implement me") } func (m mockedPusher) WriteHeader(_ int) { panic("implement me") } func (m mockedPusher) Push(_ string, _ *http.PushOptions) error { panic("implement me") } type mockedResponseWriter struct { http.ResponseWriter } func (m mockedResponseWriter) Header() http.Header { return m.ResponseWriter.Header() } func (m mockedResponseWriter) Write(bytes []byte) (int, error) { return m.ResponseWriter.Write(bytes) } func (m mockedResponseWriter) WriteHeader(statusCode int) { m.ResponseWriter.WriteHeader(statusCode) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/rest/handler/authhandler.go
rest/handler/authhandler.go
package handler import ( "context" "errors" "net/http" "net/http/httputil" "github.com/golang-jwt/jwt/v4" "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/rest/internal/response" "github.com/zeromicro/go-zero/rest/token" ) const ( jwtAudience = "aud" jwtExpire = "exp" jwtId = "jti" jwtIssueAt = "iat" jwtIssuer = "iss" jwtNotBefore = "nbf" jwtSubject = "sub" noDetailReason = "no detail reason" ) var ( errInvalidToken = errors.New("invalid auth token") errNoClaims = errors.New("no auth params") ) type ( // An AuthorizeOptions is authorize options. AuthorizeOptions struct { PrevSecret string Callback UnauthorizedCallback } // UnauthorizedCallback defines the method of unauthorized callback. UnauthorizedCallback func(w http.ResponseWriter, r *http.Request, err error) // AuthorizeOption defines the method to customize an AuthorizeOptions. AuthorizeOption func(opts *AuthorizeOptions) ) // Authorize returns an authorization middleware. func Authorize(secret string, opts ...AuthorizeOption) func(http.Handler) http.Handler { var authOpts AuthorizeOptions for _, opt := range opts { opt(&authOpts) } parser := token.NewTokenParser() return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { tok, err := parser.ParseToken(r, secret, authOpts.PrevSecret) if err != nil { unauthorized(w, r, err, authOpts.Callback) return } if !tok.Valid { unauthorized(w, r, errInvalidToken, authOpts.Callback) return } claims, ok := tok.Claims.(jwt.MapClaims) if !ok { unauthorized(w, r, errNoClaims, authOpts.Callback) return } ctx := r.Context() for k, v := range claims { switch k { case jwtAudience, jwtExpire, jwtId, jwtIssueAt, jwtIssuer, jwtNotBefore, jwtSubject: // ignore the standard claims default: ctx = context.WithValue(ctx, k, v) } } next.ServeHTTP(w, r.WithContext(ctx)) }) } } // WithPrevSecret returns an AuthorizeOption with setting previous secret. func WithPrevSecret(secret string) AuthorizeOption { return func(opts *AuthorizeOptions) { opts.PrevSecret = secret } } // WithUnauthorizedCallback returns an AuthorizeOption with setting unauthorized callback. func WithUnauthorizedCallback(callback UnauthorizedCallback) AuthorizeOption { return func(opts *AuthorizeOptions) { opts.Callback = callback } } func detailAuthLog(r *http.Request, reason string) { // discard dump error, only for debug purpose details, _ := httputil.DumpRequest(r, true) logc.Errorf(r.Context(), "authorize failed: %s\n=> %+v", reason, string(details)) } func unauthorized(w http.ResponseWriter, r *http.Request, err error, callback UnauthorizedCallback) { writer := response.NewHeaderOnceResponseWriter(w) if err != nil { detailAuthLog(r, err.Error()) } else { detailAuthLog(r, noDetailReason) } // let callback go first, to make sure we respond with user-defined HTTP header if callback != nil { callback(writer, r, err) } // if user not setting HTTP header, we set header with 401 writer.WriteHeader(http.StatusUnauthorized) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/mcp/types.go
mcp/types.go
package mcp import ( "context" sdkmcp "github.com/modelcontextprotocol/go-sdk/mcp" ) // Re-export commonly used SDK types for convenience type ( // Tool types Tool = sdkmcp.Tool CallToolParams = sdkmcp.CallToolParams CallToolResult = sdkmcp.CallToolResult CallToolRequest = sdkmcp.CallToolRequest // Content types Content = sdkmcp.Content TextContent = sdkmcp.TextContent ImageContent = sdkmcp.ImageContent AudioContent = sdkmcp.AudioContent // Prompt types Prompt = sdkmcp.Prompt PromptMessage = sdkmcp.PromptMessage GetPromptParams = sdkmcp.GetPromptParams GetPromptResult = sdkmcp.GetPromptResult // Resource types Resource = sdkmcp.Resource ResourceContents = sdkmcp.ResourceContents ReadResourceParams = sdkmcp.ReadResourceParams ReadResourceResult = sdkmcp.ReadResourceResult // Session and server types Server = sdkmcp.Server ServerSession = sdkmcp.ServerSession ServerOptions = sdkmcp.ServerOptions Implementation = sdkmcp.Implementation // Transport types SSEHandler = sdkmcp.SSEHandler StreamableHTTPHandler = sdkmcp.StreamableHTTPHandler ) // ToolHandler is a generic function signature for tool handlers. // Handlers should accept context, request, and typed arguments, and return // a result, metadata, and error. // // Deprecated: Use ToolHandlerFor directly from the SDK types. type ToolHandler[Args any, Meta any] func( ctx context.Context, req *CallToolRequest, args Args, ) (*CallToolResult, Meta, error) // PromptHandler is a function signature for prompt handlers. type PromptHandler func( ctx context.Context, req *sdkmcp.GetPromptRequest, args map[string]string, ) (*GetPromptResult, error) // ResourceHandler is a function signature for resource handlers. type ResourceHandler func( ctx context.Context, req *sdkmcp.ReadResourceRequest, uri string, ) (*ReadResourceResult, error) // AddTool registers a tool with the MCP server using type-safe generics. // The SDK automatically generates JSON schema from the Args struct tags. // // Example: // // type GreetArgs struct { // Name string `json:"name" jsonschema:"description=Name to greet"` // } // // tool := &mcp.Tool{ // Name: "greet", // Description: "Greet someone", // } // // handler := func(ctx context.Context, req *mcp.CallToolRequest, args GreetArgs) (*mcp.CallToolResult, any, error) { // return &mcp.CallToolResult{ // Content: []mcp.Content{&mcp.TextContent{Text: "Hello " + args.Name}}, // }, nil, nil // } // // mcp.AddTool(server, tool, handler) func AddTool[In, Out any](server McpServer, tool *Tool, handler func(context.Context, *CallToolRequest, In) (*CallToolResult, Out, error)) { // Access internal server - only works with mcpServerImpl if impl, ok := server.(*mcpServerImpl); ok { sdkmcp.AddTool(impl.mcpServer, tool, handler) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/mcp/server_test.go
mcp/server_test.go
package mcp import ( "bytes" "context" "net/http" "net/http/httptest" "testing" "time" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/conf" ) func TestNewMcpServer(t *testing.T) { c := McpConf{} c.Host = "localhost" c.Port = 8080 c.Mcp.Name = "test-server" c.Mcp.Version = "1.0.0" server := NewMcpServer(c) assert.NotNil(t, server) } func TestNewMcpServerWithDefaults(t *testing.T) { c := McpConf{} c.Name = "default-server" c.Host = "localhost" c.Port = 8082 server := NewMcpServer(c) impl := server.(*mcpServerImpl) // Check defaults are set assert.Equal(t, "default-server", impl.conf.Mcp.Name) assert.Equal(t, "1.0.0", impl.conf.Mcp.Version) } func TestNewMcpServerWithCORS(t *testing.T) { c := McpConf{} c.Host = "localhost" c.Port = 8083 c.Mcp.Name = "cors-server" c.Mcp.Cors = []string{"http://localhost:3000", "http://example.com"} server := NewMcpServer(c) assert.NotNil(t, server) } func TestSetupSSETransport(t *testing.T) { c := McpConf{} c.Host = "localhost" c.Port = 8084 c.Mcp.Name = "sse-server" c.Mcp.UseStreamable = false c.Mcp.SseEndpoint = "/sse" c.Mcp.MessageTimeout = 30 * time.Second c.Mcp.SseTimeout = 24 * time.Hour server := NewMcpServer(c) impl := server.(*mcpServerImpl) assert.NotNil(t, impl.httpServer) assert.False(t, impl.conf.Mcp.UseStreamable) } func TestSetupStreamableTransport(t *testing.T) { c := McpConf{} c.Host = "localhost" c.Port = 8085 c.Mcp.Name = "streamable-server" c.Mcp.UseStreamable = true c.Mcp.MessageEndpoint = "/message" c.Mcp.MessageTimeout = 30 * time.Second c.Mcp.SseTimeout = 24 * time.Hour server := NewMcpServer(c) impl := server.(*mcpServerImpl) assert.NotNil(t, impl.httpServer) assert.True(t, impl.conf.Mcp.UseStreamable) } func TestServerImplementsInterface(t *testing.T) { c := McpConf{} c.Host = "localhost" c.Port = 8086 c.Mcp.Name = "interface-test" var _ McpServer = NewMcpServer(c) } func TestAddTool(t *testing.T) { c := McpConf{} c.Host = "localhost" c.Port = 8081 c.Mcp.Name = "test-server" server := NewMcpServer(c) type Args struct { Name string `json:"name"` } tool := &Tool{ Name: "greet", Description: "Say hello", } handler := func(ctx context.Context, req *CallToolRequest, args Args) (*CallToolResult, any, error) { return &CallToolResult{ Content: []Content{ &TextContent{Text: "Hello " + args.Name}, }, }, nil, nil } // Register the tool using mcp.AddTool AddTool(server, tool, handler) } func TestAddToolWithStructuredOutput(t *testing.T) { c := McpConf{} c.Host = "localhost" c.Port = 8087 c.Mcp.Name = "structured-test" server := NewMcpServer(c) type CalculateArgs struct { A int `json:"a"` B int `json:"b"` } type CalculateResult struct { Sum int `json:"sum"` } tool := &Tool{ Name: "add", Description: "Add two numbers", } handler := func(ctx context.Context, req *CallToolRequest, args CalculateArgs) (*CallToolResult, CalculateResult, error) { result := CalculateResult{Sum: args.A + args.B} return &CallToolResult{ Content: []Content{ &TextContent{Text: "Sum calculated"}, }, }, result, nil } AddTool(server, tool, handler) } func TestServerLifecycle(t *testing.T) { c := McpConf{} c.Host = "127.0.0.1" c.Port = 0 // Use random port c.Mcp.Name = "lifecycle-test" c.Mcp.SseEndpoint = "/sse" c.Mcp.MessageEndpoint = "/message" server := NewMcpServer(c) // Test that Start and Stop can be called // We don't actually start it to avoid port conflicts in tests impl := server.(*mcpServerImpl) assert.NotNil(t, impl.httpServer) // Just verify the methods exist and can be called // Actual server start/stop is tested in integration tests defer func() { if r := recover(); r == nil { // If no panic, call stop server.Stop() } }() } func TestServerStartStop(t *testing.T) { // Create server with a unique port c := McpConf{} c.Host = "127.0.0.1" c.Port = 18080 // Use high port to avoid conflicts c.Mcp.Name = "start-stop-test" c.Mcp.SseEndpoint = "/sse" c.Mcp.MessageEndpoint = "/message" c.Mcp.SseTimeout = 1 * time.Second c.Mcp.MessageTimeout = 1 * time.Second server := NewMcpServer(c) // Test that we can call Stop even without Start // (This tests the Stop method coverage) server.Stop() } func TestServerStartActual(t *testing.T) { // Create server with specific port c := McpConf{} c.Host = "127.0.0.1" c.Port = 19080 // Use specific high port c.Mcp.Name = "actual-start-test" c.Mcp.SseEndpoint = "/sse" c.Mcp.MessageEndpoint = "/message" c.Mcp.SseTimeout = 1 * time.Second c.Mcp.MessageTimeout = 1 * time.Second server := NewMcpServer(c) // Start server in goroutine go func() { server.Start() // This blocks until Stop() is called }() // Give server time to start time.Sleep(300 * time.Millisecond) // Make a test request to the SSE endpoint to trigger the handler callback client := &http.Client{Timeout: 500 * time.Millisecond} req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:19080/sse", nil) if err == nil { req.Header.Set("Accept", "text/event-stream") resp, err := client.Do(req) if err == nil { resp.Body.Close() // Server is responding - this proves Start() worked // and the SSE handler callback was called assert.True(t, resp.StatusCode == http.StatusOK || resp.StatusCode > 0) } } // Stop the server server.Stop() // Give it time to shutdown time.Sleep(100 * time.Millisecond) } func TestServerStartStreamable(t *testing.T) { // Test with Streamable transport c := McpConf{} c.Host = "127.0.0.1" c.Port = 19081 c.Mcp.Name = "streamable-start-test" c.Mcp.UseStreamable = true c.Mcp.SseEndpoint = "/sse" c.Mcp.MessageEndpoint = "/message" c.Mcp.SseTimeout = 1 * time.Second c.Mcp.MessageTimeout = 1 * time.Second server := NewMcpServer(c) // Start server in goroutine go func() { server.Start() }() // Give server time to start time.Sleep(300 * time.Millisecond) // Make a GET request first (SSE connection) client := &http.Client{Timeout: 500 * time.Millisecond} req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:19081/message", nil) if err == nil { req.Header.Set("Accept", "text/event-stream") resp, err := client.Do(req) if err == nil { resp.Body.Close() // GET request should work assert.True(t, resp.StatusCode > 0) } } // Also make a POST request (for message) jsonData := []byte(`{"jsonrpc":"2.0","method":"ping","id":1}`) req2, err := http.NewRequest(http.MethodPost, "http://127.0.0.1:19081/message", bytes.NewBuffer(jsonData)) if err == nil { req2.Header.Set("Content-Type", "application/json") resp, err := client.Do(req2) if err == nil { resp.Body.Close() // POST request should also work assert.True(t, resp.StatusCode > 0) } } // Stop the server server.Stop() // Give it time to shutdown time.Sleep(100 * time.Millisecond) } func TestSSEHandlerCallback(t *testing.T) { c := McpConf{} c.Host = "127.0.0.1" c.Port = 0 c.Mcp.Name = "sse-handler-test" c.Mcp.UseStreamable = false c.Mcp.SseEndpoint = "/sse" c.Mcp.MessageEndpoint = "/message" server := NewMcpServer(c) impl := server.(*mcpServerImpl) // Verify the server is set up correctly assert.NotNil(t, impl.mcpServer) assert.False(t, impl.conf.Mcp.UseStreamable) } func TestStreamableHandlerCallback(t *testing.T) { c := McpConf{} c.Host = "127.0.0.1" c.Port = 0 c.Mcp.Name = "streamable-handler-test" c.Mcp.UseStreamable = true c.Mcp.SseEndpoint = "/sse" c.Mcp.MessageEndpoint = "/message" server := NewMcpServer(c) impl := server.(*mcpServerImpl) // Verify the server is set up correctly assert.NotNil(t, impl.mcpServer) assert.True(t, impl.conf.Mcp.UseStreamable) } func TestSSEEndpointAccess(t *testing.T) { c := McpConf{} c.Host = "127.0.0.1" c.Port = 0 c.Mcp.Name = "sse-endpoint-test" c.Mcp.UseStreamable = false c.Mcp.SseEndpoint = "/sse" server := NewMcpServer(c) impl := server.(*mcpServerImpl) // Create a test request req := httptest.NewRequest(http.MethodGet, "/sse", nil) req.Header.Set("Accept", "text/event-stream") // The server should be configured with SSE endpoints assert.NotNil(t, impl.httpServer) assert.Equal(t, "/sse", impl.conf.Mcp.SseEndpoint) } func TestStreamableEndpointAccess(t *testing.T) { c := McpConf{} c.Host = "127.0.0.1" c.Port = 0 c.Mcp.Name = "streamable-endpoint-test" c.Mcp.UseStreamable = true c.Mcp.MessageEndpoint = "/message" server := NewMcpServer(c) impl := server.(*mcpServerImpl) // The server should be configured with streamable endpoints assert.NotNil(t, impl.httpServer) assert.Equal(t, "/message", impl.conf.Mcp.MessageEndpoint) } func TestConfig(t *testing.T) { var c McpConf err := conf.FillDefault(&c) assert.NoError(t, err) assert.Equal(t, "1.0.0", c.Mcp.Version) assert.Equal(t, "/sse", c.Mcp.SseEndpoint) assert.Equal(t, "/message", c.Mcp.MessageEndpoint) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/mcp/config.go
mcp/config.go
package mcp import ( "time" "github.com/zeromicro/go-zero/rest" ) // McpConf defines the configuration for an MCP server. // It embeds rest.RestConf for HTTP server settings // and adds MCP-specific configuration options. type McpConf struct { rest.RestConf Mcp struct { // Name is the server name reported in initialize responses Name string `json:",optional"` // Version is the server version reported in initialize responses Version string `json:",default=1.0.0"` // UseStreamable when true uses Streamable HTTP transport (2025-03-26 spec), // otherwise uses SSE transport (2024-11-05 spec) UseStreamable bool `json:",default=false"` // SseEndpoint is the path for Server-Sent Events connections // Used for SSE transport mode SseEndpoint string `json:",default=/sse"` // MessageEndpoint is the path for JSON-RPC requests // Used for Streamable HTTP transport mode MessageEndpoint string `json:",default=/message"` // Cors contains allowed CORS origins Cors []string `json:",optional"` // SseTimeout is the maximum time allowed for SSE connections SseTimeout time.Duration `json:",default=24h"` // MessageTimeout is the maximum time allowed for request execution MessageTimeout time.Duration `json:",default=30s"` } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/mcp/config_test.go
mcp/config_test.go
package mcp import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/conf" ) func TestMcpConfDefaults(t *testing.T) { // Test default values are set correctly jsonConfig := `name: test-service port: 8080 mcp: name: test-mcp-server version: 1.0.0 ` var c McpConf err := conf.LoadFromYamlBytes([]byte(jsonConfig), &c) assert.NoError(t, err) // Check default values assert.Equal(t, "test-mcp-server", c.Mcp.Name) assert.Equal(t, "1.0.0", c.Mcp.Version) assert.Equal(t, "/sse", c.Mcp.SseEndpoint) assert.Equal(t, "/message", c.Mcp.MessageEndpoint) assert.Equal(t, 30*time.Second, c.Mcp.MessageTimeout) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/mcp/server.go
mcp/server.go
package mcp import ( "net/http" sdkmcp "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/rest" ) // McpServer defines the interface for Model Context Protocol servers using the official SDK type McpServer interface { // Start starts the HTTP server Start() // Stop stops the HTTP server Stop() } type mcpServerImpl struct { conf McpConf httpServer *rest.Server mcpServer *sdkmcp.Server } // NewMcpServer creates a new MCP server using the official SDK func NewMcpServer(c McpConf) McpServer { // Create the underlying rest HTTP server var httpServer *rest.Server if len(c.Mcp.Cors) == 0 { httpServer = rest.MustNewServer(c.RestConf) } else { httpServer = rest.MustNewServer(c.RestConf, rest.WithCors(c.Mcp.Cors...)) } // Set defaults if len(c.Mcp.Name) == 0 { c.Mcp.Name = c.Name } if len(c.Mcp.Version) == 0 { c.Mcp.Version = "1.0.0" } // Create the MCP SDK server impl := &sdkmcp.Implementation{ Name: c.Mcp.Name, Version: c.Mcp.Version, } mcpServer := sdkmcp.NewServer(impl, nil) s := &mcpServerImpl{ conf: c, httpServer: httpServer, mcpServer: mcpServer, } // Choose transport based on configuration if c.Mcp.UseStreamable { s.setupStreamableTransport() } else { s.setupSSETransport() } return s } // Start implements McpServer. func (s *mcpServerImpl) Start() { logx.Infof("Starting MCP server %s v%s on %s:%d", s.conf.Mcp.Name, s.conf.Mcp.Version, s.conf.Host, s.conf.Port) s.httpServer.Start() } // Stop implements McpServer. func (s *mcpServerImpl) Stop() { logx.Info("Stopping MCP server") s.httpServer.Stop() } // setupSSETransport configures the server to use SSE transport (2024-11-05 spec) func (s *mcpServerImpl) setupSSETransport() { // Create SSE handler that returns our MCP server for each connection handler := sdkmcp.NewSSEHandler(func(r *http.Request) *sdkmcp.Server { logx.Infof("New SSE connection from %s", r.RemoteAddr) return s.mcpServer }, nil) // Register the SSE endpoint s.httpServer.AddRoute(rest.Route{ Method: http.MethodGet, Path: s.conf.Mcp.SseEndpoint, Handler: handler.ServeHTTP, }, rest.WithSSE(), rest.WithTimeout(s.conf.Mcp.SseTimeout)) // The SSE handler also handles POST requests to message endpoints // We need to route those as well s.httpServer.AddRoute(rest.Route{ Method: http.MethodPost, Path: s.conf.Mcp.SseEndpoint, Handler: handler.ServeHTTP, }, rest.WithTimeout(s.conf.Mcp.MessageTimeout)) } // setupStreamableTransport configures the server to use Streamable HTTP transport (2025-03-26 spec) func (s *mcpServerImpl) setupStreamableTransport() { // Create Streamable HTTP handler handler := sdkmcp.NewStreamableHTTPHandler(func(r *http.Request) *sdkmcp.Server { logx.Infof("New streamable connection from %s", r.RemoteAddr) return s.mcpServer }, nil) // Register the message endpoint (handles both GET for SSE and POST for messages) s.httpServer.AddRoute(rest.Route{ Method: http.MethodGet, Path: s.conf.Mcp.MessageEndpoint, Handler: handler.ServeHTTP, }, rest.WithSSE(), rest.WithTimeout(s.conf.Mcp.SseTimeout)) s.httpServer.AddRoute(rest.Route{ Method: http.MethodPost, Path: s.conf.Mcp.MessageEndpoint, Handler: handler.ServeHTTP, }, rest.WithTimeout(s.conf.Mcp.MessageTimeout)) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/main.go
main.go
package main import ( "github.com/jesseduffield/lazygit/pkg/app" ) // These values may be set by the build script via the LDFLAGS argument var ( commit string date string version string buildSource = "unknown" ) func main() { ldFlagsBuildInfo := &app.BuildInfo{ Commit: commit, Date: date, Version: version, BuildSource: buildSource, } app.Start(ldFlagsBuildInfo, nil) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/tasks/async_handler.go
pkg/tasks/async_handler.go
package tasks import ( "github.com/jesseduffield/gocui" "github.com/sasha-s/go-deadlock" ) // the purpose of an AsyncHandler is to ensure that if we have multiple long-running // requests, we only handle the result of the latest one. For example, if I am // searching for 'abc' and I have to type 'a' then 'b' then 'c' and each keypress // dispatches a request to search for things with the string so-far, we'll be searching // for 'a', 'ab', and 'abc', and it may be that 'abc' comes back first, then 'ab', // then 'a' and we don't want to display the result for 'a' just because it came // back last. AsyncHandler keeps track of the order in which things were dispatched // so that we can ignore anything that comes back late. type AsyncHandler struct { currentId int lastId int mutex deadlock.Mutex onReject func() onWorker func(func(gocui.Task) error) } func NewAsyncHandler(onWorker func(func(gocui.Task) error)) *AsyncHandler { return &AsyncHandler{ mutex: deadlock.Mutex{}, onWorker: onWorker, } } func (self *AsyncHandler) Do(f func() func()) { self.mutex.Lock() self.currentId++ id := self.currentId self.mutex.Unlock() self.onWorker(func(gocui.Task) error { after := f() self.handle(after, id) return nil }) } // f here is expected to be a function that doesn't take long to run func (self *AsyncHandler) handle(f func(), id int) { self.mutex.Lock() defer self.mutex.Unlock() if id < self.lastId { if self.onReject != nil { self.onReject() } return } self.lastId = id f() }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/tasks/async_handler_test.go
pkg/tasks/async_handler_test.go
package tasks import ( "fmt" "sync" "testing" "github.com/jesseduffield/gocui" "github.com/stretchr/testify/assert" ) func TestAsyncHandler(t *testing.T) { wg := sync.WaitGroup{} wg.Add(2) onWorker := func(f func(gocui.Task) error) { go func() { _ = f(gocui.NewFakeTask()) }() } handler := NewAsyncHandler(onWorker) handler.onReject = func() { wg.Done() } result := 0 wg2 := sync.WaitGroup{} wg2.Add(1) handler.Do(func() func() { wg2.Wait() return func() { fmt.Println("setting to 1") result = 1 } }) handler.Do(func() func() { return func() { fmt.Println("setting to 2") result = 2 wg.Done() wg2.Done() } }) wg.Wait() assert.EqualValues(t, 2, result) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/tasks/tasks.go
pkg/tasks/tasks.go
package tasks import ( "bufio" "fmt" "io" "os/exec" "sync" "time" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/commands/oscommands" "github.com/jesseduffield/lazygit/pkg/utils" "github.com/sasha-s/go-deadlock" "github.com/sirupsen/logrus" ) // This file revolves around running commands that will be output to the main panel // in the gui. If we're flicking through the commits panel, we want to invoke a // `git show` command for each commit, but we don't want to read the entire output // at once (because that would slow things down); we just want to fill the panel // and then read more as the user scrolls down. We also want to ensure that we're only // ever running one `git show` command at time, and that we only have one command // writing its output to the main panel at a time. const THROTTLE_TIME = time.Millisecond * 30 // we use this to check if the system is under stress right now. Hopefully this makes sense on other machines const COMMAND_START_THRESHOLD = time.Millisecond * 10 type ViewBufferManager struct { // this blocks until the task has been properly stopped stopCurrentTask func() // this is what we write the output of the task to. It's typically a view writer io.Writer waitingMutex deadlock.Mutex taskIDMutex deadlock.Mutex Log *logrus.Entry newTaskID int readLines chan LinesToRead taskKey string onNewKey func() // beforeStart is the function that is called before starting a new task beforeStart func() refreshView func() onEndOfInput func() // see docs/dev/Busy.md // A gocui task is not the same thing as the tasks defined in this file. // A gocui task simply represents the fact that lazygit is busy doing something, // whereas the tasks in this file are about rendering content to a view. newGocuiTask func() gocui.Task // if the user flicks through a heap of items, with each one // spawning a process to render something to the main view, // it can slow things down quite a bit. In these situations we // want to throttle the spawning of processes. throttle bool } type LinesToRead struct { // Total number of lines to read Total int // Number of lines after which we have read enough to fill the view, and can // do an initial refresh. Only set for the initial read request; -1 for // subsequent requests. InitialRefreshAfter int // Function to call after reading the lines is done Then func() } func (self *ViewBufferManager) GetTaskKey() string { return self.taskKey } func NewViewBufferManager( log *logrus.Entry, writer io.Writer, beforeStart func(), refreshView func(), onEndOfInput func(), onNewKey func(), newGocuiTask func() gocui.Task, ) *ViewBufferManager { return &ViewBufferManager{ Log: log, writer: writer, beforeStart: beforeStart, refreshView: refreshView, onEndOfInput: onEndOfInput, readLines: nil, onNewKey: onNewKey, newGocuiTask: newGocuiTask, } } func (self *ViewBufferManager) ReadLines(n int) { if self.readLines != nil { go utils.Safe(func() { self.readLines <- LinesToRead{Total: n, InitialRefreshAfter: -1} }) } } func (self *ViewBufferManager) ReadToEnd(then func()) { if self.readLines != nil { go utils.Safe(func() { self.readLines <- LinesToRead{Total: -1, InitialRefreshAfter: -1, Then: then} }) } else if then != nil { then() } } func (self *ViewBufferManager) NewCmdTask(start func() (*exec.Cmd, io.Reader), prefix string, linesToRead LinesToRead, onDoneFn func()) func(TaskOpts) error { return func(opts TaskOpts) error { var onDoneOnce sync.Once var onFirstPageShownOnce sync.Once onFirstPageShown := func() { onFirstPageShownOnce.Do(func() { opts.InitialContentLoaded() }) } onDone := func() { if onDoneFn != nil { onDoneOnce.Do(onDoneFn) } onFirstPageShown() } if self.throttle { self.Log.Info("throttling task") time.Sleep(THROTTLE_TIME) } select { case <-opts.Stop: onDone() return nil default: } startTime := time.Now() cmd, r := start() timeToStart := time.Since(startTime) done := make(chan struct{}) go utils.Safe(func() { select { case <-done: // The command finished and did not have to be preemptively stopped before the next command. // No need to throttle. self.throttle = false case <-opts.Stop: // we use the time it took to start the program as a way of checking if things // are running slow at the moment. This is admittedly a crude estimate, but // the point is that we only want to throttle when things are running slow // and the user is flicking through a bunch of items. self.throttle = time.Since(startTime) < THROTTLE_TIME && timeToStart > COMMAND_START_THRESHOLD // Kill the still-running command. The only reason to do this is to save CPU usage // when flicking through several very long diffs when diff.algorithm = histogram is // being used, in which case multiple git processes continue to calculate expensive // diffs in the background even though they have been stopped already. // // Unfortunately this will do nothing on Windows, so Windows users will have to live // with the higher CPU usage. if err := oscommands.TerminateProcessGracefully(cmd); err != nil { self.Log.Errorf("error when trying to terminate cmd task: %v; Command: %v %v", err, cmd.Path, cmd.Args) } // close the task's stdout pipe (or the pty if we're using one) to make the command terminate onDone() } }) loadingMutex := deadlock.Mutex{} self.readLines = make(chan LinesToRead, 1024) scanner := bufio.NewScanner(r) scanner.Split(utils.ScanLinesAndTruncateWhenLongerThanBuffer(bufio.MaxScanTokenSize)) lineChan := make(chan []byte) lineWrittenChan := make(chan struct{}) // We're reading from the scanner in a separate goroutine because on windows // if running git through a shim, we sometimes kill the parent process without // killing its children, meaning the scanner blocks forever. This solution // leaves us with a dead goroutine, but it's better than blocking all // rendering to main views. go utils.Safe(func() { defer close(lineChan) for scanner.Scan() { select { case <-opts.Stop: return case lineChan <- scanner.Bytes(): // We need to confirm the data has been fed into the view before we // pull more from the scanner because the scanner uses the same backing // array and we don't want to be mutating that while it's being written <-lineWrittenChan } } }) loaded := false go utils.Safe(func() { ticker := time.NewTicker(time.Millisecond * 200) defer ticker.Stop() select { case <-opts.Stop: return case <-ticker.C: loadingMutex.Lock() if !loaded { self.beforeStart() _, _ = self.writer.Write([]byte("loading...")) self.refreshView() } loadingMutex.Unlock() } }) go utils.Safe(func() { isViewStale := true writeToView := func(content []byte) { isViewStale = true _, _ = self.writer.Write(content) } refreshViewIfStale := func() { if isViewStale { self.refreshView() isViewStale = false } } outer: for { select { case <-opts.Stop: break outer case linesToRead := <-self.readLines: callThen := func() { if linesToRead.Then != nil { linesToRead.Then() } } for i := 0; linesToRead.Total == -1 || i < linesToRead.Total; i++ { var ok bool var line []byte select { case <-opts.Stop: callThen() break outer case line, ok = <-lineChan: // process line below } loadingMutex.Lock() if !loaded { self.beforeStart() if prefix != "" { writeToView([]byte(prefix)) } loaded = true } loadingMutex.Unlock() if !ok { // if we're here then there's nothing left to scan from the source // so we're at the EOF and can flush the stale content self.onEndOfInput() callThen() break outer } writeToView(append(line, '\n')) lineWrittenChan <- struct{}{} if i+1 == linesToRead.InitialRefreshAfter { // We have read enough lines to fill the view, so do a first refresh // here to show what we have. Continue reading and refresh again at // the end to make sure the scrollbar has the right size. refreshViewIfStale() } } refreshViewIfStale() onFirstPageShown() callThen() } } self.readLines = nil refreshViewIfStale() select { case <-opts.Stop: // If we stopped the task, don't block waiting for it; this could cause a delay if // the process takes a while until it actually terminates. We still want to call // Wait to reclaim any resources, but do it on a background goroutine, and ignore // any errors. go func() { _ = cmd.Wait() }() default: if err := cmd.Wait(); err != nil { self.Log.Errorf("Unexpected error when running cmd task: %v; Failed command: %v %v", err, cmd.Path, cmd.Args) } } // calling this here again in case the program ended on its own accord onDone() close(done) close(lineWrittenChan) }) self.readLines <- linesToRead <-done return nil } } // Close closes the task manager, killing whatever task may currently be running func (self *ViewBufferManager) Close() { if self.stopCurrentTask == nil { return } c := make(chan struct{}) go utils.Safe(func() { self.stopCurrentTask() c <- struct{}{} }) select { case <-c: return case <-time.After(3 * time.Second): fmt.Println("cannot kill child process") } } // different kinds of tasks: // 1) command based, where the manager can be asked to read more lines, but the command can be killed // 2) string based, where the manager can also be asked to read more lines type TaskOpts struct { // Channel that tells the task to stop, because another task wants to run. Stop chan struct{} // Only for tasks which are long-running, where we read more lines sporadically. // We use this to keep track of when a user's action is complete (i.e. all views // have been refreshed to display the results of their action) InitialContentLoaded func() } func (self *ViewBufferManager) NewTask(f func(TaskOpts) error, key string) error { gocuiTask := self.newGocuiTask() var completeTaskOnce sync.Once completeGocuiTask := func() { completeTaskOnce.Do(func() { gocuiTask.Done() }) } go utils.Safe(func() { defer completeGocuiTask() self.taskIDMutex.Lock() self.newTaskID++ taskID := self.newTaskID if self.GetTaskKey() != key && self.onNewKey != nil { self.onNewKey() } self.taskKey = key self.taskIDMutex.Unlock() self.waitingMutex.Lock() self.taskIDMutex.Lock() if taskID < self.newTaskID { self.waitingMutex.Unlock() self.taskIDMutex.Unlock() return } self.taskIDMutex.Unlock() if self.stopCurrentTask != nil { self.stopCurrentTask() } self.readLines = nil stop := make(chan struct{}) notifyStopped := make(chan struct{}) var once sync.Once onStop := func() { close(stop) <-notifyStopped } self.stopCurrentTask = func() { once.Do(onStop) } self.waitingMutex.Unlock() if err := f(TaskOpts{Stop: stop, InitialContentLoaded: completeGocuiTask}); err != nil { self.Log.Error(err) // might need an onError callback } close(notifyStopped) }) return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/tasks/tasks_test.go
pkg/tasks/tasks_test.go
package tasks import ( "bytes" "io" "os/exec" "reflect" "strings" "sync" "testing" "time" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazygit/pkg/utils" ) func getCounter() (func(), func() int) { counter := 0 return func() { counter++ }, func() int { return counter } } func TestNewCmdTaskInstantStop(t *testing.T) { writer := bytes.NewBuffer(nil) beforeStart, getBeforeStartCallCount := getCounter() refreshView, getRefreshViewCallCount := getCounter() onEndOfInput, getOnEndOfInputCallCount := getCounter() onNewKey, getOnNewKeyCallCount := getCounter() onDone, getOnDoneCallCount := getCounter() task := gocui.NewFakeTask() newTask := func() gocui.Task { return task } manager := NewViewBufferManager( utils.NewDummyLog(), writer, beforeStart, refreshView, onEndOfInput, onNewKey, newTask, ) stop := make(chan struct{}) reader := bytes.NewBufferString("test") start := func() (*exec.Cmd, io.Reader) { // not actually starting this because it's not necessary cmd := exec.Command("blah") close(stop) return cmd, reader } fn := manager.NewCmdTask(start, "prefix\n", LinesToRead{20, -1, nil}, onDone) _ = fn(TaskOpts{Stop: stop, InitialContentLoaded: func() { task.Done() }}) callCountExpectations := []struct { expected int actual int name string }{ {0, getBeforeStartCallCount(), "beforeStart"}, {1, getRefreshViewCallCount(), "refreshView"}, {0, getOnEndOfInputCallCount(), "onEndOfInput"}, {0, getOnNewKeyCallCount(), "onNewKey"}, {1, getOnDoneCallCount(), "onDone"}, } for _, expectation := range callCountExpectations { if expectation.actual != expectation.expected { t.Errorf("expected %s to be called %d times, got %d", expectation.name, expectation.expected, expectation.actual) } } if task.Status() != gocui.TaskStatusDone { t.Errorf("expected task status to be 'done', got '%s'", task.FormatStatus()) } expectedContent := "" actualContent := writer.String() if actualContent != expectedContent { t.Errorf("expected writer to receive the following content: \n%s\n. But instead it received: %s", expectedContent, actualContent) } } func TestNewCmdTask(t *testing.T) { writer := bytes.NewBuffer(nil) beforeStart, getBeforeStartCallCount := getCounter() refreshView, getRefreshViewCallCount := getCounter() onEndOfInput, getOnEndOfInputCallCount := getCounter() onNewKey, getOnNewKeyCallCount := getCounter() onDone, getOnDoneCallCount := getCounter() task := gocui.NewFakeTask() newTask := func() gocui.Task { return task } manager := NewViewBufferManager( utils.NewDummyLog(), writer, beforeStart, refreshView, onEndOfInput, onNewKey, newTask, ) stop := make(chan struct{}) reader := bytes.NewBufferString("test") start := func() (*exec.Cmd, io.Reader) { // not actually starting this because it's not necessary cmd := exec.Command("blah") return cmd, reader } fn := manager.NewCmdTask(start, "prefix\n", LinesToRead{20, -1, nil}, onDone) wg := sync.WaitGroup{} wg.Go(func() { time.Sleep(100 * time.Millisecond) close(stop) }) _ = fn(TaskOpts{Stop: stop, InitialContentLoaded: func() { task.Done() }}) wg.Wait() callCountExpectations := []struct { expected int actual int name string }{ {1, getBeforeStartCallCount(), "beforeStart"}, {1, getRefreshViewCallCount(), "refreshView"}, {1, getOnEndOfInputCallCount(), "onEndOfInput"}, {0, getOnNewKeyCallCount(), "onNewKey"}, {1, getOnDoneCallCount(), "onDone"}, } for _, expectation := range callCountExpectations { if expectation.actual != expectation.expected { t.Errorf("expected %s to be called %d times, got %d", expectation.name, expectation.expected, expectation.actual) } } if task.Status() != gocui.TaskStatusDone { t.Errorf("expected task status to be 'done', got '%s'", task.FormatStatus()) } expectedContent := "prefix\ntest\n" actualContent := writer.String() if actualContent != expectedContent { t.Errorf("expected writer to receive the following content: \n%s\n. But instead it received: %s", expectedContent, actualContent) } } // A dummy reader that simply yields as many blank lines as requested. The only // thing we want to do with the output is count the number of lines. type BlankLineReader struct { totalLinesToYield int linesYielded int } func (d *BlankLineReader) Read(p []byte) (n int, err error) { if d.totalLinesToYield == d.linesYielded { return 0, io.EOF } d.linesYielded++ p[0] = '\n' return 1, nil } func TestNewCmdTaskRefresh(t *testing.T) { type scenario struct { name string totalTaskLines int linesToRead LinesToRead expectedLineCountsOnRefresh []int } scenarios := []scenario{ { "total < initialRefreshAfter", 150, LinesToRead{100, 120, nil}, []int{100}, }, { "total == initialRefreshAfter", 150, LinesToRead{100, 100, nil}, []int{100}, }, { "total > initialRefreshAfter", 150, LinesToRead{100, 50, nil}, []int{50, 100}, }, { "initialRefreshAfter == -1", 150, LinesToRead{100, -1, nil}, []int{100}, }, { "totalTaskLines < initialRefreshAfter", 25, LinesToRead{100, 50, nil}, []int{25}, }, { "totalTaskLines between total and initialRefreshAfter", 75, LinesToRead{100, 50, nil}, []int{50, 75}, }, } for _, s := range scenarios { writer := bytes.NewBuffer(nil) lineCountsOnRefresh := []int{} refreshView := func() { lineCountsOnRefresh = append(lineCountsOnRefresh, strings.Count(writer.String(), "\n")) } task := gocui.NewFakeTask() newTask := func() gocui.Task { return task } manager := NewViewBufferManager( utils.NewDummyLog(), writer, func() {}, refreshView, func() {}, func() {}, newTask, ) stop := make(chan struct{}) reader := BlankLineReader{totalLinesToYield: s.totalTaskLines} start := func() (*exec.Cmd, io.Reader) { // not actually starting this because it's not necessary cmd := exec.Command("blah") return cmd, &reader } fn := manager.NewCmdTask(start, "", s.linesToRead, func() {}) wg := sync.WaitGroup{} wg.Go(func() { time.Sleep(100 * time.Millisecond) close(stop) }) _ = fn(TaskOpts{Stop: stop, InitialContentLoaded: func() { task.Done() }}) wg.Wait() if !reflect.DeepEqual(lineCountsOnRefresh, s.expectedLineCountsOnRefresh) { t.Errorf("%s: expected line counts on refresh: %v, got %v", s.name, s.expectedLineCountsOnRefresh, lineCountsOnRefresh) } } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/logs/logs.go
pkg/logs/logs.go
package logs import ( "io" "log" "os" "github.com/sirupsen/logrus" ) // It's important that this package does not depend on any other package because we // may want to import it from anywhere, and we don't want to create a circular dependency // (because Go refuses to compile circular dependencies). // Global is a global logger that can be used anywhere in the app, for // _development purposes only_. I want to avoid global variables when possible, // so if you want to log something that's printed when the -debug flag is set, // you'll need to ensure the struct you're working with has a logger field ( // and most of them do). // Global is only available if the LAZYGIT_LOG_PATH environment variable is set. var Global *logrus.Entry func init() { logPath := os.Getenv("LAZYGIT_LOG_PATH") if logPath != "" { Global = NewDevelopmentLogger(logPath) } } func NewProductionLogger() *logrus.Entry { logger := logrus.New() logger.Out = io.Discard logger.SetLevel(logrus.ErrorLevel) return formatted(logger) } func NewDevelopmentLogger(logPath string) *logrus.Entry { logger := logrus.New() logger.SetLevel(getLogLevel()) file, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o666) if err != nil { log.Fatalf("Unable to log to log file: %v", err) } logger.SetOutput(file) return formatted(logger) } func formatted(log *logrus.Logger) *logrus.Entry { // highly recommended: tail -f development.log | humanlog // https://github.com/aybabtme/humanlog log.Formatter = &logrus.JSONFormatter{} return log.WithFields(logrus.Fields{}) } func getLogLevel() logrus.Level { strLevel := os.Getenv("LOG_LEVEL") level, err := logrus.ParseLevel(strLevel) if err != nil { return logrus.DebugLevel } return level }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false