stub

package
v0.12.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 18, 2024 License: BSD-3-Clause Imports: 23 Imported by: 8

README

STUB

This package provides a set of utilities and helper methods to call a REST or RPC (over websocket) By using this package many of the boilerplate codes are not necessary anymore.

REST example:

package main

import (
	"context"
	"net/http"

	"github.com/clubpay/ronykit/kit/stub"
)

func main() {
	ctx := context.Background()
	s := stub.New("webhook.site", stub.Secure())
	httpCtx := s.REST().
		SetMethod(http.MethodGet).
		SetHeader("Content-Type", "application/json").
		SetPath("/22fda9e7-1660-406e-b11e-993e070f175e").
		SetQuery("someKey", "someValue").
		Run(ctx)
	defer httpCtx.Release()
}

REST

Response Handler

When you call a REST endpoint, you can use SetResponseHandler to handle the response. There are a few helper methods to write handlers for different response status codes. Also, you use DefaultResponseHandler to set a default handler for all status codes, which are not handled by other handlers.

package main

import (
	"context"

	"github.com/clubpay/ronykit/kit"
	"github.com/clubpay/ronykit/kit/stub"
)

type ErrorMessage struct {
	Message string `json:"message"`
}

type SuccessMessage struct {
	Message string `json:"message"`
}

func main() {
	ctx := context.Background()
	s := stub.New("webhook.site", stub.Secure())
	httpCtx := s.REST().
		POST("/someendPoint/slug1").
		SetHeader("Content-Type", "application/json").
		SetQuery("someKey", "someValue").
		SetResponseHandler(
			400,
			func(ctx context.Context, r stub.RESTResponse) *stub.Error {
				res := &ErrorMessage{}
				err := stub.WrapError(kit.UnmarshalMessage(r.GetBody(), res))
				if err != nil {
					return err
				}

				return stub.NewErrorWithMsg(res)
			},
		).
		DefaultResponseHandler(
			func(ctx context.Context, r stub.RESTResponse) *stub.Error {
				res := &SuccessMessage{}

				return stub.WrapError(kit.UnmarshalMessage(r.GetBody(), res))
			},
		).
		Run(ctx)
	defer httpCtx.Release()

  if httpCtx.Error() != nil {
		// handle error
	}
}


Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrBadHandshake = websocket.ErrBadHandshake
)

Functions

This section is empty.

Types

type CompressionLevel added in v0.10.39

type CompressionLevel int
const (
	CompressionBestSpeed       CompressionLevel = flate.BestSpeed
	CompressionBestCompression CompressionLevel = flate.BestCompression
)

type Dialer added in v0.10.30

type Dialer = websocket.Dialer

type Error

type Error struct {
	// contains filtered or unexported fields
}

func NewError

func NewError(code int, item string) *Error

func NewErrorWithMsg

func NewErrorWithMsg(msg kit.Message) *Error

func WrapError

func WrapError(err error) *Error

func (Error) Code

func (err Error) Code() int

func (Error) Error

func (err Error) Error() string

func (Error) Is

func (err Error) Is(target error) bool

func (Error) Item

func (err Error) Item() string

func (Error) Msg

func (err Error) Msg() kit.Message

func (Error) Unwrap

func (err Error) Unwrap() error
type Header map[string]string

type OnConnectHandler

type OnConnectHandler func(ctx *WebsocketCtx)

type Option

type Option func(cfg *config)

func DumpTo

func DumpTo(w io.Writer) Option

func Name

func Name(name string) Option

func Secure

func Secure() Option

func SkipTLSVerify

func SkipTLSVerify() Option

func WithDialTimeout

func WithDialTimeout(timeout time.Duration) Option

func WithHTTPProxy added in v0.11.26

func WithHTTPProxy(proxyURL string, timeout time.Duration) Option

WithHTTPProxy returns an Option that sets the dialer to the provided HTTP proxy. example formats:

localhost:9050
username:password@localhost:9050
localhost:9050

func WithLogger

func WithLogger(l kit.Logger) Option

func WithReadTimeout

func WithReadTimeout(timeout time.Duration) Option

func WithSocksProxy added in v0.11.26

func WithSocksProxy(proxyURL string) Option

WithSocksProxy returns an Option that sets the dialer to the provided SOCKS5 proxy. example format: localhost:9050

func WithTracePropagator added in v0.9.8

func WithTracePropagator(tp kit.TracePropagator) Option

func WithWriteTimeout

func WithWriteTimeout(timeout time.Duration) Option

type PreDialHandler added in v0.10.30

type PreDialHandler func(d *Dialer)

type RESTCtx

type RESTCtx struct {
	// contains filtered or unexported fields
}

func HTTP added in v0.11.25

func HTTP(rawURL string, opts ...Option) (*RESTCtx, error)

func (*RESTCtx) AppendQuery added in v0.11.25

func (hc *RESTCtx) AppendQuery(key, value string) *RESTCtx

func (*RESTCtx) AutoRun

func (hc *RESTCtx) AutoRun(
	ctx context.Context, route string, enc kit.Encoding, m kit.Message,
) *RESTCtx

AutoRun is a helper method, which fills the request based on the input arguments. It checks the route which is a path pattern, and fills the dynamic url params based on the `m`'s `tag` keys. Example:

type Request struct {
		ID int64 `json:"id"`
		Name string `json:"name"`
}

AutoRun(

	context.Background(),
  "/something/:id/:name",
  kit.JSON,
  &Request{ID: 10, Name: "customName"},

)

Is equivalent to:

SetPath("/something/10/customName"). Run(context.Background())

func (*RESTCtx) CopyBody

func (hc *RESTCtx) CopyBody(dst []byte) []byte

CopyBody copies the body to `dst`. It creates a new slice and returns it if dst is nil.

func (*RESTCtx) DefaultResponseHandler

func (hc *RESTCtx) DefaultResponseHandler(h RESTResponseHandler) *RESTCtx

func (*RESTCtx) DumpRequest

func (hc *RESTCtx) DumpRequest() string

func (*RESTCtx) DumpRequestTo

func (hc *RESTCtx) DumpRequestTo(w io.Writer) *RESTCtx

DumpRequestTo accepts a writer and will write the request dump to it when Run is executed.

Please refer to DumpResponseTo

func (*RESTCtx) DumpResponse

func (hc *RESTCtx) DumpResponse() string

func (*RESTCtx) DumpResponseTo

func (hc *RESTCtx) DumpResponseTo(w io.Writer) *RESTCtx

DumpResponseTo accepts a writer and will write the response dump to it when Run is executed. Example:

httpCtx := s.REST().
							DumpRequestTo(os.Stdout).
							DumpResponseTo(os.Stdout).
							GET("https//google.com").
							Run(ctx)
defer httpCtx.Release()

**YOU MUST NOT USE httpCtx after httpCtx.Release() is called.**

func (*RESTCtx) Err

func (hc *RESTCtx) Err() *Error

Err returns the error if any occurred during the execution.

func (*RESTCtx) Error

func (hc *RESTCtx) Error() error

Error returns the error if any occurred during the execution.

func (*RESTCtx) GET

func (hc *RESTCtx) GET(path string) *RESTCtx

func (*RESTCtx) GetBody

func (hc *RESTCtx) GetBody() []byte

GetBody returns the body, but please note that the returned slice is only valid until Release is called. If you need to use the body after releasing RESTCtx then use CopyBody method.

func (*RESTCtx) GetHeader

func (hc *RESTCtx) GetHeader(key string) string

GetHeader returns the header value for the key in the response

func (*RESTCtx) OPTIONS

func (hc *RESTCtx) OPTIONS(path string) *RESTCtx

func (*RESTCtx) PATCH

func (hc *RESTCtx) PATCH(path string) *RESTCtx

func (*RESTCtx) POST

func (hc *RESTCtx) POST(path string) *RESTCtx

func (*RESTCtx) PUT

func (hc *RESTCtx) PUT(path string) *RESTCtx

func (*RESTCtx) ReadResponseBody added in v0.11.17

func (hc *RESTCtx) ReadResponseBody(w io.Writer) *RESTCtx

ReadResponseBody reads the response body to the provided writer. It MUST be called after Run or AutoRun.

func (*RESTCtx) Release

func (hc *RESTCtx) Release()

Release frees the allocated internal resources to be re-used. You MUST NOT refer to any method of this object after calling this method, if you call any method after Release has been called, the result is unpredictable.

func (*RESTCtx) Run

func (hc *RESTCtx) Run(ctx context.Context) *RESTCtx

func (*RESTCtx) SetBody

func (hc *RESTCtx) SetBody(body []byte) *RESTCtx

func (*RESTCtx) SetBodyErr added in v0.11.17

func (hc *RESTCtx) SetBodyErr(body []byte, err error) *RESTCtx

SetBodyErr is a helper method, which is useful when we want to pass the marshaler function directly without checking the error, before passing it to the SetBody method. example:

restCtx.SetBodyErr(json.Marshal(m))

Is equivalent to:

b, err := json.Marshal(m)
if err != nil {
	// handle err
}
restCtx.SetBody(b)

func (*RESTCtx) SetHeader

func (hc *RESTCtx) SetHeader(key, value string) *RESTCtx

func (*RESTCtx) SetHeaderMap added in v0.11.17

func (hc *RESTCtx) SetHeaderMap(kv map[string]string) *RESTCtx

func (*RESTCtx) SetMethod

func (hc *RESTCtx) SetMethod(method string) *RESTCtx

func (*RESTCtx) SetOKHandler added in v0.10.9

func (hc *RESTCtx) SetOKHandler(h RESTResponseHandler) *RESTCtx

func (*RESTCtx) SetPath

func (hc *RESTCtx) SetPath(path string) *RESTCtx

func (*RESTCtx) SetQuery

func (hc *RESTCtx) SetQuery(key, value string) *RESTCtx

func (*RESTCtx) SetQueryMap added in v0.11.17

func (hc *RESTCtx) SetQueryMap(kv map[string]string) *RESTCtx

func (*RESTCtx) SetResponseHandler

func (hc *RESTCtx) SetResponseHandler(statusCode int, h RESTResponseHandler) *RESTCtx

func (*RESTCtx) StatusCode

func (hc *RESTCtx) StatusCode() int

StatusCode returns the status code of the response

type RESTOption

type RESTOption func(cfg *restConfig)

func WithHeader added in v0.11.5

func WithHeader(key, value string) RESTOption

func WithHeaderMap added in v0.11.5

func WithHeaderMap(hdr map[string]string) RESTOption

func WithPreflightREST

func WithPreflightREST(h ...RESTPreflightHandler) RESTOption

WithPreflightREST register one or many handlers to run in sequence before actually making requests.

type RESTPreflightHandler

type RESTPreflightHandler func(r *fasthttp.Request)

type RESTResponse

type RESTResponse interface {
	StatusCode() int
	GetBody() []byte
	GetHeader(key string) string
}

type RESTResponseHandler

type RESTResponseHandler func(ctx context.Context, r RESTResponse) *Error

type RPCContainerHandler

type RPCContainerHandler func(ctx context.Context, c kit.IncomingRPCContainer)

type RPCMessageHandler

type RPCMessageHandler func(ctx context.Context, msg kit.Message, hdr Header, err error)

type RPCPreflightHandler added in v0.9.5

type RPCPreflightHandler func(req *WebsocketRequest)

type Stub

type Stub struct {
	// contains filtered or unexported fields
}

func New

func New(hostPort string, opts ...Option) *Stub

func (*Stub) REST

func (s *Stub) REST(opt ...RESTOption) *RESTCtx

func (*Stub) Websocket

func (s *Stub) Websocket(opts ...WebsocketOption) *WebsocketCtx

type WebsocketCtx

type WebsocketCtx struct {
	// contains filtered or unexported fields
}

func (*WebsocketCtx) BinaryMessage

func (wCtx *WebsocketCtx) BinaryMessage(
	ctx context.Context, predicate string, req, res kit.Message,
	cb RPCMessageHandler,
) error

func (*WebsocketCtx) Connect

func (wCtx *WebsocketCtx) Connect(ctx context.Context, path string) error

func (*WebsocketCtx) Disconnect

func (wCtx *WebsocketCtx) Disconnect() error

func (*WebsocketCtx) Do added in v0.9.2

func (wCtx *WebsocketCtx) Do(ctx context.Context, req WebsocketRequest) error

Do send a message to the websocket server and waits for the response. If the callback is not nil, then make sure you provide a context with deadline or timeout, otherwise you will leak goroutines.

func (*WebsocketCtx) NetConn added in v0.10.30

func (wCtx *WebsocketCtx) NetConn() net.Conn

NetConn returns the underlying net.Conn, ONLY for advanced use cases

func (*WebsocketCtx) Stats added in v0.10.40

func (wCtx *WebsocketCtx) Stats() WebsocketStats

func (*WebsocketCtx) TextMessage

func (wCtx *WebsocketCtx) TextMessage(
	ctx context.Context, predicate string, req, res kit.Message,
	cb RPCMessageHandler,
) error

type WebsocketOption

type WebsocketOption func(cfg *wsConfig)

func WithAutoReconnect

func WithAutoReconnect(b bool) WebsocketOption

func WithCompression added in v0.10.39

func WithCompression(c CompressionLevel) WebsocketOption

func WithConcurrency added in v0.10.15

func WithConcurrency(n int) WebsocketOption

func WithCustomDialerBuilder

func WithCustomDialerBuilder(b func() *websocket.Dialer) WebsocketOption

func WithDefaultHandler

func WithDefaultHandler(h RPCContainerHandler) WebsocketOption

func WithHandler

func WithHandler(predicate string, h RPCContainerHandler) WebsocketOption

func WithOnConnectHandler

func WithOnConnectHandler(f OnConnectHandler) WebsocketOption

func WithPingTime

func WithPingTime(t time.Duration) WebsocketOption

func WithPreDialHandler added in v0.10.30

func WithPreDialHandler(f PreDialHandler) WebsocketOption

func WithPredicateKey

func WithPredicateKey(key string) WebsocketOption

func WithPreflightRPC added in v0.9.5

func WithPreflightRPC(h ...RPCPreflightHandler) WebsocketOption

WithPreflightRPC register one or many handlers to run in sequence before actually making requests.

func WithRecoverPanic added in v0.10.16

func WithRecoverPanic(f func(err any)) WebsocketOption

func WithUpgradeHeader

func WithUpgradeHeader(key string, values ...string) WebsocketOption

type WebsocketRequest added in v0.9.2

type WebsocketRequest struct {
	// ID is optional, if you don't set it, a random string will be generated
	ID string
	// Predicate is the routing key for the message, which will be added to the kit.OutgoingRPCContainer
	Predicate string
	// MessageType is the type of the message, either websocket.TextMessage or websocket.BinaryMessage
	MessageType int
	ReqMsg      kit.Message
	// ResMsg is the message that will be used to unmarshal the response.
	// You should pass a pointer to the struct that you want to unmarshal the response into.
	// If Callback is nil, then this field will be ignored.
	ResMsg kit.Message
	// ReqHdr is the headers that will be added to the kit.OutgoingRPCContainer
	ReqHdr Header
	// Callback is the callback that will be called when the response is received.
	// If this is nil, the response will be ignored. However, the response will be caught by
	// the default handler if it is set.
	Callback RPCMessageHandler
}

type WebsocketStats added in v0.10.40

type WebsocketStats struct {
	// ReadBytes is the total number of bytes read from the current websocket connection
	ReadBytes uint64
	// ReadBytesTotal is the total number of bytes read since WebsocketCtx creation
	ReadBytesTotal uint64
	// WriteBytes is the total number of bytes written to the current websocket connection
	WriteBytes uint64
	// WriteBytesTotal is the total number of bytes written since WebsocketCtx creation
	WriteBytesTotal uint64
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL