code
stringlengths
22
960k
docstring
stringlengths
20
17.8k
func_name
stringlengths
1
245
language
stringclasses
1 value
repo
stringlengths
6
57
path
stringlengths
4
226
url
stringlengths
43
277
license
stringclasses
7 values
func WithTarget(targetUrl string) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http target option can not set nil protocol") } targetUrl = strings.TrimSpace(targetUrl) if targetUrl != "" { var err error var target *url.URL target, err = url.Parse(targetUrl) if err !...
WithTarget sets the outbound recipient of cloudevents when using an HTTP request.
WithTarget
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithHeader(key, value string) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http header option can not set nil protocol") } key = strings.TrimSpace(key) if key != "" { if p.RequestTemplate == nil { p.RequestTemplate = &nethttp.Request{ Method: nethttp.MethodPost...
WithHeader sets an additional default outbound header for all cloudevents when using an HTTP request.
WithHeader
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithHost(value string) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http host option can not set nil protocol") } value = strings.TrimSpace(value) if value != "" { if p.RequestTemplate == nil { p.RequestTemplate = &nethttp.Request{ Method: nethttp.MethodPost, ...
WithHost sets the outbound host header for all cloud events when using an HTTP request
WithHost
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithShutdownTimeout(timeout time.Duration) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http shutdown timeout option can not set nil protocol") } p.ShutdownTimeout = timeout return nil } }
WithShutdownTimeout sets the shutdown timeout when the http server is being shutdown.
WithShutdownTimeout
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithReadTimeout(timeout time.Duration) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http read timeout option can not set nil protocol") } if timeout < 0 { return fmt.Errorf("http read timeout must not be negative") } p.readTimeout = &timeout return nil } }
WithReadTimeout overwrites the default read timeout (600s) of the http server. The specified timeout must not be negative. A timeout of 0 disables read timeouts in the http server.
WithReadTimeout
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithWriteTimeout(timeout time.Duration) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http write timeout option can not set nil protocol") } if timeout < 0 { return fmt.Errorf("http write timeout must not be negative") } p.writeTimeout = &timeout return nil } }
WithWriteTimeout overwrites the default write timeout (600s) of the http server. The specified timeout must not be negative. A timeout of 0 disables write timeouts in the http server.
WithWriteTimeout
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithPort(port int) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http port option can not set nil protocol") } if port < 0 || port > 65535 { return fmt.Errorf("http port option was given an invalid port: %d", port) } if err := checkListen(p, "http port option"); err !=...
WithPort sets the listening port for StartReceiver. Only one of WithListener or WithPort is allowed.
WithPort
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithListener(l net.Listener) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http listener option can not set nil protocol") } if err := checkListen(p, "http listener"); err != nil { return err } p.listener.Store(l) return nil } }
WithListener sets the listener for StartReceiver. Only one of WithListener or WithPort is allowed.
WithListener
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithPath(path string) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http path option can not set nil protocol") } path = strings.TrimSpace(path) if len(path) == 0 { return fmt.Errorf("http path option was given an invalid path: %q", path) } p.Path = path return nil...
WithPath sets the path to receive cloudevents on for HTTP transports.
WithPath
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithMethod(method string) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http method option can not set nil protocol") } method = strings.TrimSpace(method) if method != "" { if p.RequestTemplate == nil { p.RequestTemplate = &nethttp.Request{} } p.RequestTemplate...
WithMethod sets the HTTP verb (GET, POST, PUT, etc.) to use when using an HTTP request.
WithMethod
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithMiddleware(middleware Middleware) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http middleware option can not set nil protocol") } p.middleware = append(p.middleware, middleware) return nil } }
WithMiddleware adds an HTTP middleware to the transport. It may be specified multiple times. Middleware is applied to everything before it. For example `NewClient(WithMiddleware(foo), WithMiddleware(bar))` would result in `bar(foo(original))`.
WithMiddleware
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithRoundTripperDecorator(decorator func(roundTripper nethttp.RoundTripper) nethttp.RoundTripper) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http round tripper option can not set nil protocol") } if p.roundTripper == nil { if p.Client == nil { p.roundTripper = netht...
WithRoundTripperDecorator decorates the default HTTP RoundTripper chosen.
WithRoundTripperDecorator
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithGetHandlerFunc(fn nethttp.HandlerFunc) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http GET handler func can not set nil protocol") } p.GetHandlerFn = fn return nil } }
WithGetHandlerFunc sets the http GET handler func
WithGetHandlerFunc
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithOptionsHandlerFunc(fn nethttp.HandlerFunc) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http OPTIONS handler func can not set nil protocol") } p.OptionsHandlerFn = fn return nil } }
WithOptionsHandlerFunc sets the http OPTIONS handler func
WithOptionsHandlerFunc
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithIsRetriableFunc(isRetriable IsRetriable) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("isRetriable handler func can not set nil protocol") } if isRetriable == nil { return fmt.Errorf("isRetriable handler can not be nil") } p.isRetriableFunc = isRetriable return n...
WithIsRetriableFunc sets the function that gets called to determine if an error should be retried. If not set, the defaultIsRetriableFunc is used.
WithIsRetriableFunc
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithRequestDataAtContextMiddleware() Option { return WithMiddleware(func(next nethttp.Handler) nethttp.Handler { return nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) { ctx := WithRequestDataAtContext(r.Context(), r) next.ServeHTTP(w, r.WithContext(ctx)) }) }) }
WithRequestDataAtContextMiddleware adds to the Context RequestData. This enables a user's dispatch handler to inspect HTTP request information by retrieving it from the Context.
WithRequestDataAtContextMiddleware
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func forceClose(tr *Protocol) { ctx, cancel := context.WithCancel(context.Background()) go func() { _ = tr.OpenInbound(ctx) }() cancel() }
Force a transport to close its server/listener by cancelling StartReceiver
forceClose
go
cloudevents/sdk-go
v2/protocol/http/options_test.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options_test.go
Apache-2.0
func copyHeadersEnsure(from http.Header, to *http.Header) { if len(from) > 0 { if *to == nil { *to = http.Header{} } copyHeaders(from, *to) } }
Ensure to is a non-nil map before copying
copyHeadersEnsure
go
cloudevents/sdk-go
v2/protocol/http/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/protocol.go
Apache-2.0
func (p *Protocol) Receive(ctx context.Context) (binding.Message, error) { if ctx == nil { return nil, fmt.Errorf("nil Context") } msg, fn, err := p.Respond(ctx) // No-op the response when finish is invoked. if msg != nil { return binding.WithFinish(msg, func(err error) { if fn != nil { _ = fn(ctx, nil...
Receive the next incoming HTTP request as a CloudEvent. Returns non-nil error if the incoming HTTP request fails to parse as a CloudEvent Returns io.EOF if the receiver is closed.
Receive
go
cloudevents/sdk-go
v2/protocol/http/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/protocol.go
Apache-2.0
func (p *Protocol) Respond(ctx context.Context) (binding.Message, protocol.ResponseFn, error) { if ctx == nil { return nil, nil, fmt.Errorf("nil Context") } select { case in, ok := <-p.incoming: if !ok { return nil, nil, io.EOF } if in.msg == nil { return nil, in.respFn, in.err } return in.msg, ...
Respond receives the next incoming HTTP request as a CloudEvent and waits for the response callback to invoked before continuing. Returns non-nil error if the incoming HTTP request fails to parse as a CloudEvent Returns io.EOF if the receiver is closed.
Respond
go
cloudevents/sdk-go
v2/protocol/http/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/protocol.go
Apache-2.0
func (p *Protocol) ServeHTTP(rw http.ResponseWriter, req *http.Request) { // always apply limiter first using req context ok, reset, err := p.limiter.Allow(req.Context(), req) if err != nil { p.incoming <- msgErr{msg: nil, err: fmt.Errorf("unable to acquire rate limit token: %w", err)} rw.WriteHeader(http.Status...
ServeHTTP implements http.Handler. Blocks until ResponseFn is invoked.
ServeHTTP
go
cloudevents/sdk-go
v2/protocol/http/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/protocol.go
Apache-2.0
func (p *Protocol) GetListeningPort() int { if listener := p.listener.Load(); listener != nil { if tcpAddr, ok := listener.(net.Listener).Addr().(*net.TCPAddr); ok { return tcpAddr.Port } } return -1 }
GetListeningPort returns the listening port. Returns -1 if it's not listening.
GetListeningPort
go
cloudevents/sdk-go
v2/protocol/http/protocol_lifecycle.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/protocol_lifecycle.go
Apache-2.0
func (p *Protocol) listen() (net.Listener, error) { if p.listener.Load() == nil { port := 8080 if p.Port != -1 { port = p.Port if port < 0 || port > 65535 { return nil, fmt.Errorf("invalid port %d", port) } } var err error var listener net.Listener if listener, err = net.Listen("tcp", fmt.Spri...
listen if not already listening, update t.Port
listen
go
cloudevents/sdk-go
v2/protocol/http/protocol_lifecycle.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/protocol_lifecycle.go
Apache-2.0
func (p *Protocol) GetPath() string { path := strings.TrimSpace(p.Path) if len(path) > 0 { return path } return "/" // default }
GetPath returns the path the transport is hosted on. If the path is '/', the transport will handle requests on any URI. To discover the true path a request was received on, inspect the context from Receive(cxt, ...) with TransportContextFrom(ctx).
GetPath
go
cloudevents/sdk-go
v2/protocol/http/protocol_lifecycle.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/protocol_lifecycle.go
Apache-2.0
func attachMiddleware(h http.Handler, middleware []Middleware) http.Handler { for _, m := range middleware { h = m(h) } return h }
attachMiddleware attaches the HTTP middleware to the specified handler.
attachMiddleware
go
cloudevents/sdk-go
v2/protocol/http/protocol_lifecycle.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/protocol_lifecycle.go
Apache-2.0
func resetBody(req *http.Request, body []byte) { if req == nil || req.Body == nil { return } req.Body = io.NopCloser(bytes.NewReader(body)) // do not modify existing GetBody function if req.GetBody == nil { req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(body)), nil } ...
reset body to allow it to be read multiple times, e.g. when retrying http requests
resetBody
go
cloudevents/sdk-go
v2/protocol/http/protocol_retry.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/protocol_retry.go
Apache-2.0
func NewResult(statusCode int, messageFmt string, args ...interface{}) protocol.Result { return &Result{ StatusCode: statusCode, Format: messageFmt, Args: args, } }
NewResult returns a fully populated http Result that should be used as a transport.Result.
NewResult
go
cloudevents/sdk-go
v2/protocol/http/result.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/result.go
Apache-2.0
func NewRetriesResult(result protocol.Result, retries int, startTime time.Time, attempts []protocol.Result) protocol.Result { rr := &RetriesResult{ Result: result, Retries: retries, Duration: time.Since(startTime), } if len(attempts) > 0 { rr.Attempts = attempts } return rr }
NewRetriesResult returns a http RetriesResult that should be used as a transport.Result without retries
NewRetriesResult
go
cloudevents/sdk-go
v2/protocol/http/retries_result.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/retries_result.go
Apache-2.0
func (e *RetriesResult) Is(target error) bool { return protocol.ResultIs(e.Result, target) }
Is returns if the target error is a RetriesResult type checking target.
Is
go
cloudevents/sdk-go
v2/protocol/http/retries_result.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/retries_result.go
Apache-2.0
func NewEventsFromHTTPRequest(req *nethttp.Request) ([]event.Event, error) { msg := NewMessageFromHttpRequest(req) return binding.ToEvents(context.Background(), msg, msg.BodyReader) }
NewEventsFromHTTPRequest returns a batched set of Events from a HTTP Request
NewEventsFromHTTPRequest
go
cloudevents/sdk-go
v2/protocol/http/utility.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/utility.go
Apache-2.0
func NewEventsFromHTTPResponse(resp *nethttp.Response) ([]event.Event, error) { msg := NewMessageFromHttpResponse(resp) return binding.ToEvents(context.Background(), msg, msg.BodyReader) }
NewEventsFromHTTPResponse returns a batched set of Events from a HTTP Response
NewEventsFromHTTPResponse
go
cloudevents/sdk-go
v2/protocol/http/utility.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/utility.go
Apache-2.0
func NewHTTPRequestFromEvent(ctx context.Context, url string, event event.Event) (*nethttp.Request, error) { if err := event.Validate(); err != nil { return nil, err } req, err := nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, url, nil) if err != nil { return nil, err } if err := WriteRequest(ctx, (*...
NewHTTPRequestFromEvent creates a http.Request object that can be used with any http.Client for a singular event. This is an HTTP POST action to the provided url.
NewHTTPRequestFromEvent
go
cloudevents/sdk-go
v2/protocol/http/utility.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/utility.go
Apache-2.0
func NewHTTPRequestFromEvents(ctx context.Context, url string, events []event.Event) (*nethttp.Request, error) { // Sending batch events is quite straightforward, as there is only JSON format, so a simple implementation. for _, e := range events { if err := e.Validate(); err != nil { return nil, err } } var ...
NewHTTPRequestFromEvents creates a http.Request object that can be used with any http.Client for sending a batched set of events. This is an HTTP POST action to the provided url.
NewHTTPRequestFromEvents
go
cloudevents/sdk-go
v2/protocol/http/utility.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/utility.go
Apache-2.0
func IsHTTPBatch(header nethttp.Header) bool { return header.Get(ContentType) == event.ApplicationCloudEventsBatchJSON }
IsHTTPBatch returns if the current http.Request or http.Response is a batch event operation, by checking the header `Content-Type` value.
IsHTTPBatch
go
cloudevents/sdk-go
v2/protocol/http/utility.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/utility.go
Apache-2.0
func WriteRequest(ctx context.Context, m binding.Message, httpRequest *http.Request, transformers ...binding.Transformer) error { structuredWriter := (*httpRequestWriter)(httpRequest) binaryWriter := (*httpRequestWriter)(httpRequest) _, err := binding.Write( ctx, m, structuredWriter, binaryWriter, transfo...
WriteRequest fills the provided httpRequest with the message m. Using context you can tweak the encoding processing (more details on binding.Write documentation).
WriteRequest
go
cloudevents/sdk-go
v2/protocol/http/write_request.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/write_request.go
Apache-2.0
func (b *httpRequestWriter) setBody(body io.Reader) error { rc, ok := body.(io.ReadCloser) if !ok && body != nil { rc = io.NopCloser(body) } b.Body = rc if body != nil { switch v := body.(type) { case *bytes.Buffer: b.ContentLength = int64(v.Len()) buf := v.Bytes() b.GetBody = func() (io.ReadCloser,...
setBody is a cherry-pick of the implementation in http.NewRequestWithContext
setBody
go
cloudevents/sdk-go
v2/protocol/http/write_request.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/write_request.go
Apache-2.0
func WriteResponseWriter(ctx context.Context, m binding.Message, status int, rw http.ResponseWriter, transformers ...binding.Transformer) error { if status < 200 || status >= 600 { status = http.StatusOK } writer := &httpResponseWriter{rw: rw, status: status} _, err := binding.Write( ctx, m, writer, writ...
WriteResponseWriter writes out to the the provided httpResponseWriter with the message m. Using context you can tweak the encoding processing (more details on binding.Write documentation).
WriteResponseWriter
go
cloudevents/sdk-go
v2/protocol/http/write_responsewriter.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/write_responsewriter.go
Apache-2.0
func BenchmarkSendReceive(b *testing.B, s protocol.Sender, r protocol.Receiver) { e := test.FullEvent() m := (*binding.EventMessage)(&e) ctx := context.Background() b.ResetTimer() // Don't count setup. for i := 0; i < b.N; i++ { n := 10 // Messages to send async. g := errgroup.Group{} g.Go(func() error { ...
BenchmarkSendReceive implements a simple send/receive benchmark. Requires a sender and receiver that are connected to each other.
BenchmarkSendReceive
go
cloudevents/sdk-go
v2/protocol/test/benchmark.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/test/benchmark.go
Apache-2.0
func SendReceive(t *testing.T, ctx context.Context, in binding.Message, s protocol.Sender, r protocol.Receiver, outAssert func(binding.Message)) { t.Helper() wg := sync.WaitGroup{} wg.Add(2) // 'wait' is used to ensure that we at least wait until the Receiver // thread starts. We'll then use a 'sleep' (hoping) th...
SendReceive does s.Send(in), then it receives the message in r.Receive() and executes outAssert Halt test on error.
SendReceive
go
cloudevents/sdk-go
v2/protocol/test/test.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/test/test.go
Apache-2.0
func AssertEvent(t testing.TB, have event.Event, matchers ...EventMatcher) { err := AllOf(matchers...)(have) if err != nil { t.Fatalf("Error while matching event: %s", err.Error()) } }
AssertEvent is a "matcher like" assertion method to test the properties of an event
AssertEvent
go
cloudevents/sdk-go
v2/test/event_asserts.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_asserts.go
Apache-2.0
func AssertEventContextEquals(t testing.TB, want event.EventContext, have event.EventContext) { if err := IsContextEqualTo(want)(event.Event{Context: have}); err != nil { t.Fatalf("Error while matching event context: %s", err.Error()) } }
AssertEventContextEquals asserts that two event.Event contexts are equals
AssertEventContextEquals
go
cloudevents/sdk-go
v2/test/event_asserts.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_asserts.go
Apache-2.0
func AssertEventEquals(t testing.TB, want event.Event, have event.Event) { if err := IsEqualTo(want)(have); err != nil { t.Fatalf("Error while matching event: %s", err.Error()) } }
AssertEventEquals asserts that two event.Event are equals
AssertEventEquals
go
cloudevents/sdk-go
v2/test/event_asserts.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_asserts.go
Apache-2.0
func AnyOf(matchers ...EventMatcher) EventMatcher { return func(have event.Event) error { var errs []error for _, m := range matchers { if err := m(have); err == nil { return nil } else { errs = append(errs, err) } } var sb strings.Builder sb.WriteString("Cannot match any of the provided mat...
AnyOf returns a matcher which match if at least one of the provided matchers matches
AnyOf
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func ContainsAttributes(attrs ...spec.Kind) EventMatcher { return func(have event.Event) error { haveVersion := spec.VS.Version(have.SpecVersion()) for _, k := range attrs { attr := haveVersion.AttributeFromKind(k) if isEmpty(attr) { return fmt.Errorf("attribute name '%s' unrecognized", k.String()) } ...
ContainsAttributes checks if the event contains at least the provided context attributes
ContainsAttributes
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func ContainsExtensions(exts ...string) EventMatcher { return func(have event.Event) error { for _, ext := range exts { if _, ok := have.Extensions()[ext]; !ok { return fmt.Errorf("expecting extension '%s'", ext) } } return nil } }
ContainsExtensions checks if the event contains at least the provided extension names
ContainsExtensions
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func ContainsExactlyExtensions(exts ...string) EventMatcher { return func(have event.Event) error { // Copy in a temporary set first extsInEvent := map[string]struct{}{} for k := range have.Extensions() { extsInEvent[k] = struct{}{} } for _, ext := range exts { if _, ok := have.Extensions()[ext]; !ok ...
ContainsExactlyExtensions checks if the event contains only the provided extension names and no more
ContainsExactlyExtensions
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func HasExactlyAttributesEqualTo(want event.EventContext) EventMatcher { return func(have event.Event) error { if want.GetSpecVersion() != have.SpecVersion() { return fmt.Errorf("not matching specversion: want = '%s', got = '%s'", want.GetSpecVersion(), have.SpecVersion()) } vs := spec.VS.Version(want.GetSpec...
HasExactlyAttributesEqualTo checks if the event has exactly the provided spec attributes (excluding extension attributes)
HasExactlyAttributesEqualTo
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func HasExactlyExtensions(ext map[string]interface{}) EventMatcher { return func(have event.Event) error { if diff := cmp.Diff(ext, have.Extensions()); diff != "" { return fmt.Errorf("unexpected extensions (-want, +got) = %v", diff) } return nil } }
HasExactlyExtensions checks if the event contains exactly the provided extensions
HasExactlyExtensions
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func HasExtensions(ext map[string]interface{}) EventMatcher { return func(have event.Event) error { for k, v := range ext { if _, ok := have.Extensions()[k]; !ok { return fmt.Errorf("expecting extension '%s'", ext) } if !reflect.DeepEqual(v, have.Extensions()[k]) { return fmt.Errorf("expecting exten...
HasExtensions checks if the event contains at least the provided extensions
HasExtensions
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func HasExtensionKeys(keys []string) EventMatcher { return func(have event.Event) error { for _, k := range keys { if _, ok := have.Extensions()[k]; !ok { return fmt.Errorf("expecting extension key %q", k) } } return nil } }
HasExtensionKeys checks if the event contains the provided keys from its extensions
HasExtensionKeys
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func HasExtension(key string, value interface{}) EventMatcher { return HasExtensions(map[string]interface{}{key: value}) }
HasExtension checks if the event contains the provided extension
HasExtension
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func HasData(want []byte) EventMatcher { return func(have event.Event) error { if diff := cmp.Diff(string(want), string(have.Data())); diff != "" { return fmt.Errorf("data not matching (-want, +got) = %v", diff) } return nil } }
HasData checks if the event contains the provided data
HasData
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func DataContains(expectedContainedString string) EventMatcher { return func(have event.Event) error { dataAsString := string(have.Data()) if !strings.Contains(dataAsString, expectedContainedString) { return fmt.Errorf("data '%s' doesn't contain '%s'", dataAsString, expectedContainedString) } return nil } ...
DataContains matches that the data field of the event, converted to a string, contains the provided string
DataContains
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func HasNoData() EventMatcher { return func(have event.Event) error { if have.Data() != nil { return fmt.Errorf("expecting nil data, got = '%v'", string(have.Data())) } return nil } }
HasNoData checks if the event doesn't contain data
HasNoData
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func IsEqualTo(want event.Event) EventMatcher { return AllOf(IsContextEqualTo(want.Context), IsDataEqualTo(want)) }
IsEqualTo performs a semantic equality check of the event (like AssertEventEquals)
IsEqualTo
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func IsContextEqualTo(want event.EventContext) EventMatcher { return AllOf(HasExactlyAttributesEqualTo(want), HasExactlyExtensions(want.GetExtensions())) }
IsContextEqualTo performs a semantic equality check of the event context, including extension attributes (like AssertEventContextEquals)
IsContextEqualTo
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func IsDataEqualTo(want event.Event) EventMatcher { if want.Data() == nil { return HasNoData() } else { return HasData(want.Data()) } }
IsDataEqualTo checks if the data field matches with want
IsDataEqualTo
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func IsValid() EventMatcher { return func(have event.Event) error { if err := have.Validate(); err != nil { return fmt.Errorf("expecting valid event: %s", err.Error()) } return nil } }
IsValid checks if the event is valid
IsValid
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func IsInvalid() EventMatcher { return func(have event.Event) error { if err := have.Validate(); err == nil { return fmt.Errorf("expecting invalid event") } return nil } }
IsInvalid checks if the event is invalid
IsInvalid
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func FullEvent() event.Event { e := event.Event{ Context: event.EventContextV1{ Type: "com.example.FullEvent", Source: Source, ID: "full-event", Time: &Timestamp, DataSchema: &Schema, Subject: strptr("topic"), }.AsV1(), } e.SetExtension("exbool", true) e.SetExtensio...
FullEvent has all context attributes set and JSON string data.
FullEvent
go
cloudevents/sdk-go
v2/test/event_mocks.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_mocks.go
Apache-2.0
func MinEvent() event.Event { return event.Event{ Context: event.EventContextV1{ Type: "com.example.MinEvent", Source: Source, ID: "min-event", }.AsV1(), } }
MinEvent has only required attributes set.
MinEvent
go
cloudevents/sdk-go
v2/test/event_mocks.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_mocks.go
Apache-2.0
func FullMessage() binding.Message { ev := FullEvent() return binding.ToMessage(&ev) }
FullMessage returns the same event of FullEvent but wrapped as Message.
FullMessage
go
cloudevents/sdk-go
v2/test/event_mocks.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_mocks.go
Apache-2.0
func MinMessage() binding.Message { ev := MinEvent() return binding.ToMessage(&ev) }
MinMessage returns the same event of MinEvent but wrapped as Message.
MinMessage
go
cloudevents/sdk-go
v2/test/event_mocks.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_mocks.go
Apache-2.0
func AllVersions(events []event.Event) []event.Event { versions := spec.New() all := versions.Versions() result := make([]event.Event, len(events)*len(all)) i := 0 for _, e := range events { for _, v := range all { result[i] = e result[i].Context = v.Convert(e.Context) result[i].SetID(fmt.Sprintf("%v-%v...
AllVersions returns all versions of each event in events. ID gets a -number suffix so IDs are unique.
AllVersions
go
cloudevents/sdk-go
v2/test/event_mocks.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_mocks.go
Apache-2.0
func Events() []event.Event { return AllVersions([]event.Event{FullEvent(), MinEvent()}) }
Events is a set of test events that should be handled correctly by all event-processing code.
Events
go
cloudevents/sdk-go
v2/test/event_mocks.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_mocks.go
Apache-2.0
func WithoutExtensions(events []event.Event) []event.Event { result := make([]event.Event, len(events)) for i, e := range events { result[i] = e result[i].Context = e.Context.Clone() ctx := reflect.ValueOf(result[i].Context).Elem() ext := ctx.FieldByName("Extensions") ext.Set(reflect.Zero(ext.Type())) } r...
WithoutExtensions returns a copy of events with no Extensions. Use for testing where extensions are not supported.
WithoutExtensions
go
cloudevents/sdk-go
v2/test/helpers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/helpers.go
Apache-2.0
func MustJSON(t testing.TB, e event.Event) []byte { b, err := format.JSON.Marshal(&e) require.NoError(t, err) return b }
MustJSON marshals the event.Event to JSON structured representation or panics
MustJSON
go
cloudevents/sdk-go
v2/test/helpers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/helpers.go
Apache-2.0
func MustToEvent(t testing.TB, ctx context.Context, m binding.Message) event.Event { e, err := binding.ToEvent(ctx, m) require.NoError(t, err) return *e }
MustToEvent converts a Message to event.Event
MustToEvent
go
cloudevents/sdk-go
v2/test/helpers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/helpers.go
Apache-2.0
func ConvertEventExtensionsToString(t testing.TB, e event.Event) event.Event { out := e.Clone() for k, v := range e.Extensions() { var vParsed interface{} var err error switch v := v.(type) { case json.RawMessage: err = json.Unmarshal(v, &vParsed) require.NoError(t, err) default: vParsed, err = ty...
ConvertEventExtensionsToString returns a copy of the event.Event where all extensions are converted to strings. Fails the test if conversion fails
ConvertEventExtensionsToString
go
cloudevents/sdk-go
v2/test/helpers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/helpers.go
Apache-2.0
func TestNameOf(x interface{}) string { switch x := x.(type) { case event.Event: b, err := json.Marshal(x) if err == nil { return fmt.Sprintf("Event%s", b) } case binding.Message: return fmt.Sprintf("Message{%s}", reflect.TypeOf(x).String()) } return fmt.Sprintf("%T(%#v)", x, x) }
TestNameOf generates a string test name from x, esp. for ce.Event and ce.Message.
TestNameOf
go
cloudevents/sdk-go
v2/test/helpers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/helpers.go
Apache-2.0
func EachEvent(t *testing.T, events []event.Event, f func(*testing.T, event.Event)) { for _, e := range events { in := e t.Run(TestNameOf(in), func(t *testing.T) { f(t, in) }) } }
EachEvent runs f as a test for each event in events
EachEvent
go
cloudevents/sdk-go
v2/test/helpers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/helpers.go
Apache-2.0
func EachMessage(t *testing.T, messages []binding.Message, f func(*testing.T, binding.Message)) { for _, m := range messages { in := m t.Run(TestNameOf(in), func(t *testing.T) { f(t, in) }) } }
EachMessage runs f as a test for each message in messages
EachMessage
go
cloudevents/sdk-go
v2/test/helpers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/helpers.go
Apache-2.0
func Allocate(obj interface{}) (asPtr interface{}, asValue reflect.Value) { if obj == nil { return nil, reflect.Value{} } switch t := reflect.TypeOf(obj); t.Kind() { case reflect.Ptr: reflectPtr := reflect.New(t.Elem()) asPtr = reflectPtr.Interface() asValue = reflectPtr case reflect.Map: reflectPtr := ...
Allocate allocates a new instance of type t and returns: asPtr is of type t if t is a pointer type and of type &t otherwise asValue is a Value of type t pointing to the same data as asPtr
Allocate
go
cloudevents/sdk-go
v2/types/allocate.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/allocate.go
Apache-2.0
func ParseTimestamp(s string) (*Timestamp, error) { if s == "" { return nil, nil } tt, err := ParseTime(s) return &Timestamp{Time: tt}, err }
ParseTimestamp attempts to parse the given time assuming RFC3339 layout
ParseTimestamp
go
cloudevents/sdk-go
v2/types/timestamp.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/timestamp.go
Apache-2.0
func ParseURI(u string) *URI { if u == "" { return nil } pu, err := url.Parse(u) if err != nil { return nil } return &URI{URL: *pu} }
ParseURI attempts to parse the given string as a URI.
ParseURI
go
cloudevents/sdk-go
v2/types/uri.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/uri.go
Apache-2.0
func ParseURIRef(u string) *URIRef { if u == "" { return nil } pu, err := url.Parse(u) if err != nil { return nil } return &URIRef{URL: *pu} }
ParseURIRef attempts to parse the given string as a URI-Reference.
ParseURIRef
go
cloudevents/sdk-go
v2/types/uriref.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/uriref.go
Apache-2.0
func ParseInteger(v string) (int32, error) { // Accept floating-point but truncate to int32 as per CE spec. f, err := strconv.ParseFloat(v, 64) if err != nil { return 0, err } if f > math.MaxInt32 || f < math.MinInt32 { return 0, rangeErr(v) } return int32(f), nil }
ParseInteger parse canonical string format: decimal notation.
ParseInteger
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func ParseTime(v string) (time.Time, error) { t, err := time.Parse(time.RFC3339Nano, v) if err != nil { err := convertErr(time.Time{}, v) err.extra = ": not in RFC3339 format" return time.Time{}, err } return t, nil }
ParseTime parse canonical string format: RFC3339 with nanoseconds
ParseTime
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func Format(v interface{}) (string, error) { v, err := Validate(v) if err != nil { return "", err } switch v := v.(type) { case bool: return FormatBool(v), nil case int32: return FormatInteger(v), nil case string: return v, nil case []byte: return FormatBinary(v), nil case URI: return v.String(), n...
Format returns the canonical string format of v, where v can be any type that is convertible to a CloudEvents type.
Format
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func Validate(v interface{}) (interface{}, error) { switch v := v.(type) { case bool, int32, string, []byte: return v, nil // Already a CloudEvents type, no validation needed. case uint, uintptr, uint8, uint16, uint32, uint64: u := reflect.ValueOf(v).Uint() if u > math.MaxInt32 { return nil, rangeErr(v) ...
Validate v is a valid CloudEvents attribute value, convert it to one of: bool, int32, string, []byte, types.URI, types.URIRef, types.Timestamp
Validate
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func Clone(v interface{}) interface{} { if v == nil { return nil } switch v := v.(type) { case bool, int32, string, nil: return v // Already a CloudEvents type, no validation needed. case []byte: clone := make([]byte, len(v)) copy(clone, v) return v case url.URL: return URI{v} case *url.URL: return...
Clone v clones a CloudEvents attribute value, which is one of the valid types: bool, int32, string, []byte, types.URI, types.URIRef, types.Timestamp Returns the same type Panics if the type is not valid
Clone
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func ToBool(v interface{}) (bool, error) { v, err := Validate(v) if err != nil { return false, err } switch v := v.(type) { case bool: return v, nil case string: return ParseBool(v) default: return false, convertErr(true, v) } }
ToBool accepts a bool value or canonical "true"/"false" string.
ToBool
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func ToInteger(v interface{}) (int32, error) { v, err := Validate(v) if err != nil { return 0, err } switch v := v.(type) { case int32: return v, nil case string: return ParseInteger(v) default: return 0, convertErr(int32(0), v) } }
ToInteger accepts any numeric value in int32 range, or canonical string.
ToInteger
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func ToString(v interface{}) (string, error) { v, err := Validate(v) if err != nil { return "", err } switch v := v.(type) { case string: return v, nil default: return "", convertErr("", v) } }
ToString returns a string value unaltered. This function does not perform canonical string encoding, use one of the Format functions for that.
ToString
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func ToBinary(v interface{}) ([]byte, error) { v, err := Validate(v) if err != nil { return nil, err } switch v := v.(type) { case []byte: return v, nil case string: return base64.StdEncoding.DecodeString(v) default: return nil, convertErr([]byte(nil), v) } }
ToBinary returns a []byte value, decoding from base64 string if necessary.
ToBinary
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func ToURL(v interface{}) (*url.URL, error) { v, err := Validate(v) if err != nil { return nil, err } switch v := v.(type) { case *URI: return &v.URL, nil case URI: return &v.URL, nil case *URIRef: return &v.URL, nil case URIRef: return &v.URL, nil case string: u, err := url.Parse(v) if err != ni...
ToURL returns a *url.URL value, parsing from string if necessary.
ToURL
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func ToTime(v interface{}) (time.Time, error) { v, err := Validate(v) if err != nil { return time.Time{}, err } switch v := v.(type) { case Timestamp: return v.Time, nil case string: ts, err := time.Parse(time.RFC3339Nano, v) if err != nil { return time.Time{}, err } return ts, nil default: retu...
ToTime returns a time.Time value, parsing from RFC3339 string if necessary.
ToTime
go
cloudevents/sdk-go
v2/types/value.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value.go
Apache-2.0
func (t valueTester) convert(v interface{}) (interface{}, error) { rf := reflect.ValueOf(t.convertFn) args := []reflect.Value{reflect.ValueOf(v)} if v == nil { args[0] = reflect.Zero(rf.Type().In(0)) // Avoid the zero argument reflection trap. } result := rf.Call(args) err, _ := result[1].Interface().(error) r...
Call types.To... function, use reflection since return types differ.
convert
go
cloudevents/sdk-go
v2/types/value_test.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value_test.go
Apache-2.0
func (t *valueTester) ok(in, want interface{}, wantStr string) { t.Helper() got, err := types.Validate(in) require.NoError(t, err) assert.Equal(t, want, got) gotStr, err := types.Format(in) require.NoError(t, err) assert.Equal(t, wantStr, gotStr) x, err := t.convert(gotStr) assert.NoError(t, err) x2, err :=...
Verify round trip: convertible -> wrapped -> string -> wrapped -> clone
ok
go
cloudevents/sdk-go
v2/types/value_test.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value_test.go
Apache-2.0
func (t *valueTester) okWithDifferentFromString(in, want interface{}, wantStr string, wantAfterStr interface{}) { t.Helper() got, err := types.Validate(in) require.NoError(t, err) assert.Equal(t, want, got) gotStr, err := types.Format(in) require.NoError(t, err) assert.Equal(t, wantStr, gotStr) x, err := t.co...
Verify round trip with exception: convertible -> wrapped -> string -> different wrapped
okWithDifferentFromString
go
cloudevents/sdk-go
v2/types/value_test.go
https://github.com/cloudevents/sdk-go/blob/master/v2/types/value_test.go
Apache-2.0
func benchSimple(dbfile string, verbose bool, makeDb func(dbfile string) Db) { removeDbfiles(dbfile) db := makeDb(dbfile) defer db.Close() initSchema(db) // insert users var users []User base := time.Date(2023, 10, 1, 10, 0, 0, 0, time.Local) const nusers = 1_000_000 for i := 0; i < nusers; i++ { users = app...
Insert 1 million user rows in one database transaction. Then query all users once.
benchSimple
go
cvilsmeier/go-sqlite-bench
app/app.go
https://github.com/cvilsmeier/go-sqlite-bench/blob/master/app/app.go
Unlicense
func benchComplex(dbfile string, verbose bool, makeDb func(dbfile string) Db) { removeDbfiles(dbfile) db := makeDb(dbfile) defer db.Close() initSchema(db) const nusers = 200 const narticlesPerUser = 100 const ncommentsPerArticle = 20 if verbose { log.Printf("nusers = %d", nusers) log.Printf("narticlesPerUse...
Insert 200 users in one database transaction. Then insert 20000 articles (100 articles for each user) in another transaction. Then insert 400000 articles (20 comments for each article) in another transaction. Then query all users, articles and comments in one big JOIN statement.
benchComplex
go
cvilsmeier/go-sqlite-bench
app/app.go
https://github.com/cvilsmeier/go-sqlite-bench/blob/master/app/app.go
Unlicense
func benchMany(dbfile string, verbose bool, nusers int, makeDb func(dbfile string) Db) { removeDbfiles(dbfile) db := makeDb(dbfile) defer db.Close() initSchema(db) // insert users var users []User base := time.Date(2023, 10, 1, 10, 0, 0, 0, time.Local) for i := 0; i < nusers; i++ { users = append(users, NewUs...
Insert N users in one database transaction. Then query all users 1000 times. This benchmark is used to simluate a read-heavy use case.
benchMany
go
cvilsmeier/go-sqlite-bench
app/app.go
https://github.com/cvilsmeier/go-sqlite-bench/blob/master/app/app.go
Unlicense
func benchLarge(dbfile string, verbose bool, nsize int, makeDb func(dbfile string) Db) { removeDbfiles(dbfile) db := makeDb(dbfile) defer db.Close() initSchema(db) // insert user with large emails t0 := time.Now() base := time.Date(2023, 10, 1, 10, 0, 0, 0, time.Local) const nusers = 10_000 var users []User f...
Insert 10000 users with N bytes of row content. Then query all users. This benchmark is used to simluate reading of large (gigabytes) databases.
benchLarge
go
cvilsmeier/go-sqlite-bench
app/app.go
https://github.com/cvilsmeier/go-sqlite-bench/blob/master/app/app.go
Unlicense
func benchConcurrent(dbfile string, verbose bool, ngoroutines int, makeDb func(dbfile string) Db) { removeDbfiles(dbfile) db1 := makeDb(dbfile) driverName := db1.DriverName() initSchema(db1) // insert many users base := time.Date(2023, 10, 1, 10, 0, 0, 0, time.Local) const nusers = 1_000_000 var users []User f...
Insert one million users. Then have N goroutines query all users. This benchmark is used to simulate concurrent reads.
benchConcurrent
go
cvilsmeier/go-sqlite-bench
app/app.go
https://github.com/cvilsmeier/go-sqlite-bench/blob/master/app/app.go
Unlicense
func ToCamelCase(str string) string { return toCamelCase(str, false) }
ToCamelCase is to convert words separated by space, underscore and hyphen to camel case. Some samples. "some_words" => "someWords" "http_server" => "httpServer" "no_https" => "noHttps" "_complex__case_" => "_complex_Case_" "some words" => "someWords" "GOLANG_IS_GREAT" => "golangIsGreat"
ToCamelCase
go
huandu/xstrings
convert.go
https://github.com/huandu/xstrings/blob/master/convert.go
MIT
func ToPascalCase(str string) string { return toCamelCase(str, true) }
ToPascalCase is to convert words separated by space, underscore and hyphen to pascal case. Some samples. "some_words" => "SomeWords" "http_server" => "HttpServer" "no_https" => "NoHttps" "_complex__case_" => "_Complex_Case_" "some words" => "SomeWords" "GOLANG_IS_GREAT" => "GolangIsGreat"
ToPascalCase
go
huandu/xstrings
convert.go
https://github.com/huandu/xstrings/blob/master/convert.go
MIT
func ToSnakeCase(str string) string { return camelCaseToLowerCase(str, '_') }
ToSnakeCase can convert all upper case characters in a string to snake case format. Some samples. "FirstName" => "first_name" "HTTPServer" => "http_server" "NoHTTPS" => "no_https" "GO_PATH" => "go_path" "GO PATH" => "go_path" // space is converted to underscore. "GO-PATH" => "go_path" // hy...
ToSnakeCase
go
huandu/xstrings
convert.go
https://github.com/huandu/xstrings/blob/master/convert.go
MIT
func ToKebabCase(str string) string { return camelCaseToLowerCase(str, '-') }
ToKebabCase can convert all upper case characters in a string to kebab case format. Some samples. "FirstName" => "first-name" "HTTPServer" => "http-server" "NoHTTPS" => "no-https" "GO_PATH" => "go-path" "GO PATH" => "go-path" // space is converted to '-'. "GO-PATH" => "go-path" // hyphen is...
ToKebabCase
go
huandu/xstrings
convert.go
https://github.com/huandu/xstrings/blob/master/convert.go
MIT
func SwapCase(str string) string { var r rune var size int buf := &stringBuilder{} for len(str) > 0 { r, size = utf8.DecodeRuneInString(str) switch { case unicode.IsUpper(r): buf.WriteRune(unicode.ToLower(r)) case unicode.IsLower(r): buf.WriteRune(unicode.ToUpper(r)) default: buf.WriteRune(r...
SwapCase will swap characters case from upper to lower or lower to upper.
SwapCase
go
huandu/xstrings
convert.go
https://github.com/huandu/xstrings/blob/master/convert.go
MIT