text
stringlengths
14
100k
source
stringclasses
1 value
repo
stringclasses
810 values
language
stringclasses
13 values
<|fim_suffix|>assert.Nil(t, limit.Return()) assert.Nil(t, limit.Return()) assert.Equal(t, ErrLimitReturn, limit.Return()) } <|fim_prefix|>package syncx import ( "testing" "github.com/stretchr/testify/assert" ) func TestLimit(t *testing.T) { limit := NewLimit(2) limit.Bor<|fim_middle|>row() assert.True(t, limi...
fim
zeromicro/go-zero
go
<|fim_prefix|>package syncx import "sync" type ( // LockedCalls makes sure the calls with the same key to be called sequentially. // For example, A called F, before it's done, B called F, then B's call would not blocked, // after A's call finished, B's c<|fim_suffix|>th key<--------->executes<---->returns LockedC...
fim
zeromicro/go-zero
go
package syncx import ( "errors" "fmt" "sync" "testing" "time" ) func TestLockedCallDo(t *testing.T) { g := NewLockedCalls() v, err := g.Do("key", func() (any, error) { return "bar", nil }) if got, want := fmt.Sprintf("%v (%T)", v, v), "bar (string)"; got != want { t.Errorf("Do = %v; want %v", got, want) ...
fim
zeromicro/go-zero
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 NewManaged...
fim
zeromicro/go-zero
go
<|fim_prefix|>package syncx import ( "sync/atomic" "testing" "github.com/stretchr/te<|fim_suffix|>esource.Take()) } <|fim_middle|>stify/assert" ) func TestManagedResource(t *testing.T) { var count int32 resource := NewManagedResource(func() any { return atomic.AddInt32(&count, 1) }, func(a, b any) bool { r...
fim
zeromicro/go-zero
go
<|fim_prefix|>package syncx im<|fim_suffix|>guarantees fn can only called once. // Deprecated: use sync.OnceFunc instead. func Once(fn func()) func() { return sync.OnceFunc(fn) } <|fim_middle|>port "sync" // Once returns a func that <|endoftext|>
fim
zeromicro/go-zero
go
<|fim_prefix|>package syncx import ( "testing" "github.com<|fim_suffix|>:= 0; i < b.N; i++ { add() } assert.Equal(b, 1, v) } <|fim_middle|>/stretchr/testify/assert" ) func TestOnce(t *testing.T) { var v int add := Once(func() { v++ }) for i := 0; i < 5; i++ { add() } assert.Equal(t, 1, v) } func B...
fim
zeromicro/go-zero
go
package syncx import "sync/atomic" // An OnceGuard is used to make sure a resource can be taken once. type OnceGuard struct { done uint32 } // Taken checks if the resource is taken. func (og *OnceGuard) Taken() bool { return atomic.LoadUint32(&og.done) == 1 } // Take takes the resource, returns true on success, f...
fim
zeromicro/go-zero
go
<|fim_prefix|><|fim_suffix|>rt.False(t, guard.Take()) assert.True(t, guard.Taken()) } <|fim_middle|>package syncx import ( "testing" "github.com/stretchr/testify/assert" ) func TestOnceGuard(t *testing.T) { var guard OnceGuard assert.False(t, guard.Taken()) assert.True(t, guard.Take()) assert.True(t, guard.T...
fim
zeromicro/go-zero
go
<|fim_prefix|>package syncx import ( "sync" "time" "github.com/zeromicro/go-zero/core/timex" ) type ( // PoolOption defines the method to customize a Pool. PoolOption func(*Pool) node struct { item any next *node lastUsed time.Duration } // A Pool is used to pool resources. // The difference...
fim
zeromicro/go-zero
go
<|fim_suffix|>.Millisecond * 10) v2 := stack.Get().(int32) assert.NotEqual(t, v1, v2) } func TestNewPoolPanics(t *testing.T) { assert.Panics(t, func() { NewPool(0, create, destroy) }) } func create() any { return 1 } func destroy(_ any) { } <|fim_prefix|>package syncx import ( "sync" "sync/atomic" "testin...
fim
zeromicro/go-zero
go
<|fim_suffix|>se uses the resource with reference count incremented. func (r *RefResource) Use() error { r.lock.Lock() defer r.lock.Unlock() if r.cleaned { return ErrUseOfCleaned } r.ref++ return nil } // Clean cleans a resource with reference count decremented. func (r *RefResource) Clean() { r.lock.Lock()...
fim
zeromicro/go-zero
go
<|fim_prefix|>pack<|fim_suffix|>ean() assert.Equal(t, 1, count) cleaner.Clean() cleaner.Clean() assert.Equal(t, 1, count) assert.Equal(t, ErrUseOfCleaned, cleaner.Use()) } <|fim_middle|>age syncx import ( "testing" "github.com/stretchr/testify/assert" ) func TestRefCleaner(t *testing.T) { var count int clea...
fim
zeromicro/go-zero
go
<|fim_suffix|>nject injects the resource associated with given key. func (manager *ResourceManager) Inject(key string, resource io.Closer) { manager.lock.Lock() manager.resources[key] = resource manager.lock.Unlock() } <|fim_prefix|>package syncx import ( "io" "sync" "github.com/zeromicro/go-zero/core/errorx" )...
fim
zeromicro/go-zero
go
<|fim_suffix|>sting.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 := NewResourceManag...
fim
zeromicro/go-zero
go
<|fim_suffix|>unc() { g.lock.Lock() delete(g.calls, key) g.lock.Unlock() c.wg.Done() }() c.val, c.err = fn() } <|fim_prefix|>package syncx import "sync" type ( // SingleFlight lets the concurrent calls with the same key to share the call result. // For example, A called F, before it's done, B called F. T...
fim
zeromicro/go-zero
go
<|fim_suffix|>(&calls, 1) return <-c, nil } const n = 10 var wg sync.WaitGroup for i := 0; i < n; i++ { wg.Add(1) go func() { v, err := g.Do("key", fn) if err != nil { t.Errorf("Do error: %v", err) } if v.(string) != "bar" { t.Errorf("got %q; want %q", v, "bar") } wg.Done() }() }...
fim
zeromicro/go-zero
go
<|fim_suffix|>*SpinLock) Unlock() { atomic.StoreUint32(&sl.lock, 0) } <|fim_prefix|>package syncx import ( "runtime" "sync/atomic" ) // A SpinLock is used as a lock a fast execution. type SpinLock struct { lock uint32<|fim_middle|> } // Lock locks the SpinLock. func (sl *SpinLock) Lock() { for !sl.TryLock() { ...
fim
zeromicro/go-zero
go
<|fim_prefix|>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(...
fim
zeromicro/go-zero
go
<|fim_prefix|>package syncx import ( "errors" "time" ) // ErrTimeout is an error that indicates the borrow timeout. var ErrTimeout = errors.New("borrow timeout") // A TimeoutLimit is used to borrow with timeouts. type TimeoutLimit struct { limit Limit cond *Cond } // NewTimeoutLimit <|fim_suffix|> // Return re...
fim
zeromicro/go-zero
go
<|fim_prefix|>package syncx import ( "sync" "testing" "time" "github.com/stretchr/testify/assert" ) func TestTimeoutLimit(t *testing.T) { tests := []struc<|fim_suffix|>}) } } <|fim_middle|>t { name string interval time.Duration }{ { name: "no wait", }, { name: "wait", interval: time...
fim
zeromicro/go-zero
go
<|fim_prefix|>package sysx import "go.uber.org/automaxprocs/<|fim_suffix|>// Automatically set GOMAXPROCS to match Linux container CPU quota. func init() { maxprocs.Set(maxprocs.Logger(nil)) } <|fim_middle|>maxprocs" <|endoftext|>
fim
zeromicro/go-zero
go
<|fim_prefix|>package sysx import ( "os" "github.com/zeromicro/go-zero/core/stringx" ) var hostname stri<|fim_suffix|>tname() string { return hostname } <|fim_middle|>ng func init() { var err error hostname, err = os.Hostname() if err != nil { hostname = stringx.RandId() } } // Hostname returns the name o...
fim
zeromicro/go-zero
go
<|fim_suffix|>stname()) > 0) } <|fim_prefix|>package sysx import ( "testing" "github.co<|fim_middle|>m/stretchr/testify/assert" ) func TestHostname(t *testing.T) { assert.True(t, len(Ho<|endoftext|>
fim
zeromicro/go-zero
go
<|fim_suffix|>bles can be changed by other goroutines func (g *RoutineGroup) Run(fn func()) { g.waitGroup.Add(1) go func() { defer g.waitGroup.Done() fn() }() } // RunSafe runs the given fn in RoutineGroup, and avoid panics. // Don't reference the variables from outside, // because outside variables can be cha...
fim
zeromicro/go-zero
go
<|fim_suffix|>:= NewRoutineGroup() var once sync.Once for i := 0; i < 3; i++ { group.RunSafe(func() { once.Do(func() { panic("") }) atomic.AddInt32(&count, 1) }) } group.Wait() assert.Equal(t, int32(2), count) } <|fim_prefix|>package threading import ( "sync" "sync/atomic" "testing" "githu...
fim
zeromicro/go-zero
go
<|fim_prefix|>package threading import ( "bytes" "context" "runtime" "strconv" "github.com/zeromicro/go-zero/core/rescue" ) // GoSafe runs the given fn using another goroutine, recovers if fn panics. func GoSafe(fn func()) { go RunSafe(fn) } // GoSafeCtx runs the given fn using another goroutine, recovers if ...
fim
zeromicro/go-zero
go
package threading import ( "bytes" "context" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/lang" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/logx/logtest" ) func TestRoutineId(t *testing.T) { assert.True(t, RoutineId() > 0) } func TestRunSa...
fim
zeromicro/go-zero
go
<|fim_suffix|> that guarantees messages are taken out with the pushed order. // This runner is typically useful for Kafka consumers with parallel processing. type StableRunner[I, O any] struct { handle func(I) O consumedIndex uint64 writtenIndex uint64 ring []*struct { value chan O lock sync.M...
fim
zeromicro/go-zero
go
<|fim_prefix|>package threading import ( "math/rand" "sort" "sync" "testing" "time" "github.com/stretchr/testify/assert" ) func TestStableRunner(t *testing.T) { size := bufSize * 2 rand.NewSource(time.Now().UnixNano()) runner := NewStableRunner(func(v int) float64 { if v == 0 { time.Sleep(time.Millisec...
fim
zeromicro/go-zero
go
<|fim_suffix|> <-rp.limitChan rp.waitGroup.Done() }) task() }() return nil } // Wait waits all running tasks to be done. func (rp *TaskRunner) Wait() { rp.waitGroup.Wait() } <|fim_prefix|>package threading import ( "errors" "sync" "github.com/zeromicro/go-zero/core/lang" "github.com/zeromicro/go-ze...
fim
zeromicro/go-zero
go
package threading import ( "runtime" "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" ) func TestTaskRunner_Schedule(t *testing.T) { times := 100 pool := NewTaskRunner(runtime.NumCPU()) var counter int32 for i := 0; i < times; i++ { pool.Schedule(func() { atomic.AddInt32(&counter, 1...
fim
zeromicro/go-zero
go
package threading // A WorkerGroup is used to run given number of workers to process jobs. type WorkerGroup struct { job func() workers int } // NewWorkerGroup returns a WorkerGroup with given job and workers. func NewWorkerGroup(job func(), workers int) WorkerGroup { return WorkerGroup{ job: job, work...
fim
zeromicro/go-zero
go
<|fim_suffix|>dd(runtime.NumCPU()) group := NewWorkerGroup(func() { lock.Lock() m[fmt.Sprint(RoutineId())] = lang.Placeholder lock.Unlock() wg.Done() }, runtime.NumCPU()) go group.Start() wg.Wait() assert.Equal(t, runtime.NumCPU(), len(m)) } <|fim_prefix|>package threading import ( "fmt" "runtime" "syn...
fim
zeromicro/go-zero
go
<|fim_suffix|> func Now() time.Duration { return time.Since(initTime) } // Since returns a diff since given d. func Since(d time.Duration) time.Duration { return time.Since(initTime) - d } <|fim_prefix|>package timex import "time" // Use the long enough past time as start time, in case timex.Now() - lastTime equal...
fim
zeromicro/go-zero
go
<|fim_suffix|>w()) } } func BenchmarkTimexSince(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { _ = Since(Now()) } } <|fim_prefix|>package timex import ( "testing" "time" "gi<|fim_middle|>thub.com/stretchr/testify/assert" ) func TestRelativeTime(t *testing.T) { time.Sleep(time.Millisecond) n...
fim
zeromicro/go-zero
go
<|fim_prefix|>package timex import ( "fmt" "time" ) // ReprOfDuration returns the string representation of given duration in ms. func ReprO<|fim_suffix|>float32(duration)/float32(time.Millisecond)) } <|fim_middle|>fDuration(duration time.Duration) string { return fmt.Sprintf("%.1fms", <|endoftext|>
fim
zeromicro/go-zero
go
<|fim_prefix|>package timex import ( "testing" "time" "github.com/stretchr/testify/assert" ) func TestR<|fim_suffix|>cond+time.Millisecond*111+time.Microsecond*555)) } <|fim_middle|>eprOfDuration(t *testing.T) { assert.Equal(t, "1000.0ms", ReprOfDuration(time.Second)) assert.Equal(t, "1111.6ms", ReprOfDuration(...
fim
zeromicro/go-zero
go
<|fim_prefix|>package timex import ( "errors" "time" "github.com/zeromicro/go-zero/core/lang" ) // errTimeout indicates a timeout. var errTimeout = errors.New("timeout") type ( // Ticker interface wraps the Chan and Stop methods. Ticker interface { Chan() <-chan time.Time Stop() } // FakeTicker interfac...
fim
zeromicro/go-zero
go
<|fim_prefix|>package timex import ( "sync/atomic" "testing" "time" "github.com/stretchr/testify/assert" ) <|fim_suffix|>econd)) } <|fim_middle|> func TestRealTickerDoTick(t *testing.T) { ticker := NewTicker(time.Millisecond * 10) defer ticker.Stop() var count int for range ticker.Chan() { count++ if coun...
fim
zeromicro/go-zero
go
<|fim_prefix|>package trace import ( "context" "fmt" "os" "sync" "github.com/zeromicro/go-zero/core/logx" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" "go.opentelemetry.io/otel/exporters/stdout/s...
fim
zeromicro/go-zero
go
<|fim_prefix|>package trace import ( "context" "errors" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/logx" "go.opentelemetry.io/otel" ) func TestStartAgent(t *testing.T) { logx.Disable() const ( endpoint1 = "localhost:1234" endpoint2 = "remotehost:1234" endpoint3...
fim
zeromicro/go-zero
go
<|fim_prefix|>package trace import ( "go.opentelemetry.io/otel/attribute" semconv "go.opentelemetry.io/otel/semconv/v1.4.0" gcodes "google.golang.org/grpc/codes" ) const ( // GRPCStatusCodeKey is convention for numeric status code of a gRPC request. GRPCStatusCodeKey = attribute.Key("rpc.grpc.status_code") // R...
fim
zeromicro/go-zero
go
<|fim_suffix|>.DataLoss)) } <|fim_prefix|>packa<|fim_middle|>ge trace import ( "testing" "github.com/stretchr/testify/assert" gcodes "google.golang.org/grpc/codes" ) func TestStatusCodeAttr(t *testing.T) { assert.Equal(t, GRPCStatusCodeKey.Int(int(gcodes.DataLoss)), StatusCodeAttr(gcodes<|endoftext|>
fim
zeromicro/go-zero
go
<|fim_prefix|>package trace // TraceName represents the tracing name. const TraceName = "go-zero" // A Conf<|fim_suffix|>r example: // uptrace-dsn: 'http://project2_secret_token@localhost:14317/2' OtlpHeaders map[string]string `json:",optional"` // OtlpHttpPath represents the path for OTLP HTTP transport. // For...
fim
zeromicro/go-zero
go
<|fim_prefix|>package trace import ( "context" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/trace" "google.golang.org/protobuf/proto" ) const messageEvent = "message" var ( // MessageSent is the type of sent messages. MessageSent = messageType(RPCMessageTypeSent) // MessageReceived is the t...
fim
zeromicro/go-zero
go
<|fim_prefix|>package trace import ( "context" "testing" "github.com/stretchr/testify/assert" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/trace" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/types/d...
fim
zeromicro/go-zero
go
<|fim_suffix|>gation.Baggage{})) } <|fim_prefix|>package trace import ( "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/propagation" ) func init() { otel.SetTextMapPropagator(propagation.NewCompositeT<|fim_middle|>extMapPropagator( propagation.TraceContext{}, propa<|endoftext|>
fim
zeromicro/go-zero
go
<|fim_prefix|>package trace import "g<|fim_suffix|>rResources, attrs...) } <|fim_middle|>o.opentelemetry.io/otel/attribute" var attrResources = make([]attribute.KeyValue, 0) // AddResources add more resources in addition to configured trace name. func AddResources(attrs ...attribute.KeyValue) { attrResources = appe...
fim
zeromicro/go-zero
go
<|fim_prefix|>package trace import ( "context" "go.opentelemetry.io/otel/baggage" "go.opentelemetry.io/otel/propagation" sdktrace "go.opentelemetry.io/otel/trace" "google.golang.org/grpc/metadata" ) // assert that metadataSupplier implements the TextMapCarrier interface var _ propagation.TextMapCarrier = (*meta...
fim
zeromicro/go-zero
go
<|fim_suffix|>anic(err) } return } func TestExtractValidTraceContext(t *testing.T) { stateStr := "key1=value1,key2=value2" state, err := trace.ParseTraceState(stateStr) require.NoError(t, err) tests := []struct { name string traceparent string tracestate string sc trace.SpanContext }{ ...
fim
zeromicro/go-zero
go
<|fim_suffix|> otel.SetTracerProvider(trace.NewTracerProvider(trace.WithSyncer(me))) return me } <|fim_prefix|>package tracetest import ( "testing" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/sdk/trace/tracetest" ) // NewInMemoryExporter returns a new InMemoryExpor...
fim
zeromicro/go-zero
go
<|fim_prefix|>package trace import ( "context" "net" "strings" ztrace "github.com/zeromicro/go-zero/internal/trace" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" semconv "go.opentelemetry.io/otel/semconv/v1.4.0" "go.opentelemetry.io/otel/trace" "google.golang.org/grpc/peer" ) const localho...
fim
zeromicro/go-zero
go
<|fim_suffix|> { name: "empty", }, { name: "port only", addr: ":8080", expect: []attribute.KeyValue{ semconv.NetPeerIPKey.String(localhost), semconv.NetPeerPortKey.String("8080"), }, }, { name: "port only", addr: "192.168.0.2:8080", expect: []attribute.KeyValue{ semconv.Net...
fim
zeromicro/go-zero
go
<|fim_prefix|>package trace import "net/http" // TraceIdKey is the trace id header. // https://<|fim_suffix|>trace-id") <|fim_middle|>www.w3.org/TR/trace-context/#trace-id // May change it to trace-id afterward. var TraceIdKey = http.CanonicalHeaderKey("x-<|endoftext|>
fim
zeromicro/go-zero
go
<|fim_suffix|>turn time.Now().UnixNano() / int64(time.Millisecond) } <|fim_prefix|>package utils import ( "fmt" "time" "github.com/zeromicro/go-zero/core/timex" ) // An ElapsedTimer is a timer to track the elapsed time. type ElapsedTimer struct { start time.Duration } // NewElapsedTimer returns an ElapsedTimer....
fim
zeromicro/go-zero
go
<|fim_suffix|>eDuration(timer.ElapsedMs()) assert.Nil(t, err) assert.True(t, duration >= sleepInterval) } func TestCurrent(t *testing.T) { currentMillis := CurrentMillis() currentMicros := CurrentMicros() assert.True(t, currentMillis > 0) assert.True(t, currentMicros > 0) assert.True(t, currentMillis*1000 <= cu...
fim
zeromicro/go-zero
go
<|fim_prefix|>package utils im<|fim_suffix|>s an uuid string. func NewUuid() string { return uuid.New().String() } <|fim_middle|>port "github.com/google/uuid" // NewUuid return<|endoftext|>
fim
zeromicro/go-zero
go
<|fim_prefix|>package utils import ( "testing" "github.com/stretchr/testif<|fim_suffix|>n(NewUuid())) } <|fim_middle|>y/assert" ) func TestUuid(t *testing.T) { assert.Equal(t, 36, le<|endoftext|>
fim
zeromicro/go-zero
go
<|fim_prefix|>package utils import ( "cmp" "strconv" "strings" "github.com/zeromicro/go-zero/core/stringx" ) var replacer = stringx.NewReplacer(map[string]string{ "V": "", "v": "", "-": ".", }) // CompareVersions returns true if the first f<|fim_suffix|>are equal, otherwise false. func CompareVersions(v1, op...
fim
zeromicro/go-zero
go
<|fim_prefix|>package utils import ( "fmt" "testing<|fim_suffix|><=", true}, } for _, each := range cases { each := each t.Run(each.ver1, func(t *testing.T) { actual := CompareVersions(each.ver1, each.operator, each.ver2) assert.Equal(t, each.out, actual, fmt.Sprintf("%s vs %s", each.ver1, each.ver2)) ...
fim
zeromicro/go-zero
go
<|fim_prefix|>package validation // Valida<|fim_suffix|> Validate() error } <|fim_middle|>tor represents a validator. type Validator interface { // Validate validates the value.<|endoftext|>
fim
zeromicro/go-zero
go
<|fim_prefix|>package gateway import ( "github.com/zeromicro/go-zero/rest" "github.com/zeromicro/go-zero/zrpc" ) type ( // GatewayConf is the configuration for gateway. GatewayConf struct { rest.RestConf Upstreams []Upstream } // HttpClientConf is the configuration for an HTTP client. HttpClientConf struc...
fim
zeromicro/go-zero
go
package internal import ( "fmt" "net/http" "strings" "github.com/fullstorydev/grpcurl" "github.com/jhump/protoreflect/desc" "google.golang.org/genproto/googleapis/api/annotations" "google.golang.org/protobuf/proto" ) type Method struct { HttpMethod string HttpPath string RpcPath string } // GetMethod...
fim
zeromicro/go-zero
go
<|fim_prefix|>package internal import ( "encoding/base64" "errors" "net/http" "os" "testing" "github.com/fullstorydev/grpcurl" "github.com/jhump/protoreflect/desc" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/hash" ) const ( b64pb = `CpgBCgtoZWxsby5wcm90bxIFaGVsbG8...
fim
zeromicro/go-zero
go
<|fim_suffix|>er) OnReceiveTrailers(status *status.Status, md metadata.MD) { w, ok := h.writer.(http.ResponseWriter) if ok { for k, vs := range md { header := defaultOutgoingTrailerMatcher(k) for _, v := range vs { w.Header().Add(header, v) } } } h.Status = status } func (h *EventHandler) OnResol...
fim
zeromicro/go-zero
go
<|fim_suffix|>g{}, }, { name: "with non-http.ResponseWriter", writer: io.Discard, status: status.New(codes.OK, "success"), metadata: metadata.MD{"x-header": []string{"value"}}, expectedStatus: codes.OK, expectedHeader: nil, // headers should not be set }, } for...
fim
zeromicro/go-zero
go
<|fim_suffix|>we lowercase the key to match gRPC conventions trimmedKey := strings.TrimPrefix(k, metadataHeaderPrefix) key := strings.ToLower(fmt.Sprintf("%s%s", metadataPrefix, trimmedKey)) for _, vv := range v { headers = append(headers, key+":"+vv) } } return headers } <|fim_prefix|>package internal i...
fim
zeromicro/go-zero
go
<|fim_suffix|> "tracestate", headerVal: "key=value", expectedKey: "tracestate", }, { name: "mixed case TraceState", headerKey: "TraceState", headerVal: "key=value", expectedKey: "tracestate", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { req := httptes...
fim
zeromicro/go-zero
go
<|fim_suffix|>f bytes.Buffer if _, err := io.Copy(&buf, r.Body); err != nil { return nil, false } if buf.Len() > 0 { return &buf, true } return nil, false } <|fim_prefix|>package internal import ( "bytes" "encoding/json" "io" "net/http" "github.com/fullstorydev/grpcurl" "github.com/golang/protobuf/js...
fim
zeromicro/go-zero
go
<|fim_suffix|>r) assert.Nil(t, err4) assert.NotNil(t, parser4) } func TestNewRequestParserWithVarsAndIgnoreUnknownFields(t *testing.T) { resolver := &mockAnyResolver{} // Test with path variables and ignoreUnknownFields = true req := httptest.NewRequest("GET", "/", http.NoBody) req = pathvar.WithVars(req, map[s...
fim
zeromicro/go-zero
go
<|fim_prefix|>package internal import ( "net/http" "time" ) const grpcTimeou<|fim_suffix|>unc GetTimeout(header http.Header, defaultTimeout time.Duration) time.Duration { if timeout := header.Get(grpcTimeoutHeader); len(timeout) > 0 { if t, err := time.ParseDuration(timeout); err == nil { return t } } re...
fim
zeromicro/go-zero
go
<|fim_prefix|>package internal import ( "<|fim_suffix|>t, time.Second*5, timeout) } <|fim_middle|>net/http" "net/http/httptest" "testing" "time" "github.com/stretchr/testify/assert" ) func TestGetTimeout(t *testing.T) { req := httptest.NewRequest("GET", "/", http.NoBody) req.Header.Set(grpcTimeoutHeader, "1s"...
fim
zeromicro/go-zero
go
<|fim_prefix|>package gateway import ( "context" "fmt" "io" "net/http" "net/url" "strings" "time" "github.com/fullstorydev/grpcurl" "github.com/golang/protobuf/jsonpb" "github.com/jhump/protoreflect/grpcreflect" "github.com/zeromicro/go-zero/core/logc" "github.com/zeromicro/go-zero/core/logx" "github.com...
fim
zeromicro/go-zero
go
<|fim_prefix|>package gateway import ( "context" "errors" "io" "log" "net" "net/http" "net/http/httptest" "testing" "time" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/core/discov" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromic...
fim
zeromicro/go-zero
go
<|fim_prefix|>package devserver // Config is config for inner http server. type Config struct { <|fim_suffix|>son:",optional"` Port int `json:",default=6060"` MetricsPath string `json:",default=/metrics"` HealthPath string `json:",default=/healthz"` EnableMetrics bool `json:",default=true"` ...
fim
zeromicro/go-zero
go
<|fim_suffix|>o(func() { s := NewServer(c) s.StartAsync(c) }) } <|fim_prefix|>package devserver import ( "encoding/json" "fmt" "net/http" "net/http/pprof" "sync" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/prometheu...
fim
zeromicro/go-zero
go
<|fim_prefix|>package encoding import ( "bytes" "encoding/json" "fmt" "math" "github.com/pelletier/go-toml/v2" "github.com/titanous/json5" "github.com/zeromicro/go-zero/core/lang" "gopkg.in/yaml.v2" ) // Json5ToJson converts JSON5 data into its JSON re<|fim_suffix|>not be represented in standard JSON") } ...
fim
zeromicro/go-zero
go
<|fim_suffix|>rror(t, err) assert.Contains(t, err.Error(), "Infinity") // Negative infinity _, err = Json5ToJson([]byte(`{value: -Infinity}`)) assert.Error(t, err) assert.Contains(t, err.Error(), "Infinity") // Infinity in array _, err = Json5ToJson([]byte(`{values: [1, Infinity, 3]}`)) assert.Error(t, err) ...
fim
zeromicro/go-zero
go
<|fim_suffix|>ager) IsReady() bool { return h.ready.True() } // Name return probe name identifier func (h *healthManager) Name() string { return h.name } func newComboHealthManager() *comboHealthManager { return &comboHealthManager{} } // MarkReady sets components status to ready. func (p *comboHealthManager) Mar...
fim
zeromicro/go-zero
go
<|fim_suffix|>", func(t *testing.T) { var wg sync.WaitGroup wg.Add(10) for i := 0; i < 10; i++ { go func() { hm := NewHealthManager(probeName) hm.MarkReady() AddProbe(hm) wg.Done() }() } wg.Wait() assert.True(t, defaultHealthManager.IsReady()) }) } func TestCreateHttpHandler(t *testi...
fim
zeromicro/go-zero
go
<|fim_suffix|>x28, 0x02, 0x52, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x22, 0x21, 0x0a, 0x0f, 0x44, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x6f, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x02, 0x6f, 0x6b, 0x32, 0x48, 0x0a, 0x0e, 0x44, 0x65...
fim
zeromicro/go-zero
go
<|fim_prefix|>package mock import ( "context" "time" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) // DepositServer is used for mocking. type DepositServer struct{} // Deposit handles the deposit requests. func (*DepositServer) Deposit(_ context.Context, req *DepositRequest) (*DepositResponse...
fim
zeromicro/go-zero
go
<|fim_prefix|>package profiling import ( "runtime" "sync" "time" "github.com/grafana/pyroscope-go" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/proc" "github.com/zeromicro/go-zero/core/stat" "github.com/zeromicro/go-zero/core/threading" ) const ( defaultCheckInterval = tim...
fim
zeromicro/go-zero
go
<|fim_prefix|>package profiling import ( "sync" "testing" "time" "github.com/grafana/pyroscope-go" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/core/syncx" ) func TestStart(t *testing.T) { t.Run("profiling", func(t *testing.T) { var c Config ...
fim
zeromicro/go-zero
go
<|fim_prefix|>package trace import ( "context" "go.opentelemetry.io/otel/trace" ) func SpanIDFromContext(ctx c<|fim_suffix|>" } <|fim_middle|>ontext.Context) string { spanCtx := trace.SpanContextFromContext(ctx) if spanCtx.HasSpanID() { return spanCtx.SpanID().String() } return "" } func TraceIDFromContext...
fim
zeromicro/go-zero
go
<|fim_suffix|>ithAttributes(semconv.HTTPClientAttributesFromHTTPRequest(httptest.NewRequest(http.MethodGet, "/", nil))...), ) defer span.End() assert.NotEmpty(t, TraceIDFromContext(ctx)) assert.NotEmpty(t, SpanIDFromContext(ctx)) } func TestSpanIDFromContextEmpty(t *testing.T) { assert.Empty(t, TraceIDFromContex...
fim
zeromicro/go-zero
go
<|fim_suffix|>=24h"` // MessageTimeout is the maximum time allowed for request execution MessageTimeout time.Duration `json:",default=30s"` } } <|fim_prefix|>package mcp import ( "time" "github.com/zeromicro/go-zero/rest" ) // McpConf defines the configuration for an MC<|fim_middle|>P server. // It embeds re...
fim
zeromicro/go-zero
go
<|fim_prefix|>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 ` va...
fim
zeromicro/go-zero
go
package mcp import "net/http" // RequestMetadataExtractor extracts request metadata for downstream handlers. type RequestMetadataExtractor func(*http.Request) RequestMetadata // McpOption customizes MCP server construction. type McpOption interface { apply(*serverOptions) } type mcpOptionFunc func(*serverOptions) ...
fim
zeromicro/go-zero
go
<|fim_suffix|>thvar.Vars(r)), } for key, vals := range r.Header { metadata.Headers[http.CanonicalHeaderKey(key)] = append([]string(nil), vals...) } if r.URL != nil { for key, vals := range r.URL.Query() { metadata.Query[key] = append([]string(nil), vals...) } } return metadata } func normalizeRequest...
fim
zeromicro/go-zero
go
<|fim_prefix|>package mcp import ( "context" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/rest/pathvar" ) func TestDefaultRequestMetadataExtractor(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/sse?tenant=t1&trace=abc", nil) req.Hea...
fim
zeromicro/go-zero
go
<|fim_prefix|>package mcp import ( "context" "net/http" sdkmcp "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/rest" ) // McpServer d<|fim_suffix|> return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { metadata := normalizeRe...
fim
zeromicro/go-zero
go
<|fim_prefix|>package mcp import ( "bytes" "context" "fmt" "net" "net/http" "net/http/httptest" "testing" "time" sdkmcp "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/conf" ) func TestNewMcpServer(t *testing.T) { c := McpConf{} c.Host...
fim
zeromicro/go-zero
go
<|fim_suffix|> 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 ...
fim
zeromicro/go-zero
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 middl...
fim
zeromicro/go-zero
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) Middlew...
fim
zeromicro/go-zero
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=...
fim
zeromicro/go-zero
go
<|fim_prefix|>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.co...
fim
zeromicro/go-zero
go
<|fim_prefix|>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" "git...
fim
zeromicro/go-zero
go