Documentation
¶
Index ¶
- Constants
- func DecodeRequestJSON[T any](request *http.Request, v *T, opts DecodeOptions) error
- func DecodeResponseJSON[T any](response *http.Response, v *T, opts DecodeOptions) error
- func InjectMessageMetadata(ctx context.Context, metadata types.Metadata) context.Context
- func NewRequestWithContext[T any](ctx context.Context, method, baseURL string, options ...RequestOption[T]) (*http.Request, error)
- func RequestWithContext[T any](ctx context.Context, req *Request[T]) (*http.Request, error)
- func RetrieveMessageMetadata(ctx context.Context) types.Metadata
- type AnySender
- type AnySenderFunc
- type CoreClient
- func (core *CoreClient[T]) AppendMiddlewares(mws ...Middleware[T])
- func (core *CoreClient[T]) PrependMiddlewares(mws ...Middleware[T])
- func (core *CoreClient[T]) Send(ctx context.Context, request *Request[T], decoder ResponseDecoder) error
- func (core *CoreClient[T]) SetBaseSender(sender Sender[T])
- func (core *CoreClient[T]) SetHTTPClient(httpClient *http.Client)
- func (core *CoreClient[T]) SetRequestInterceptor(hook RequestInterceptorFunc)
- func (core *CoreClient[T]) SetResponseInterceptor(hook ResponseInterceptorFunc)
- type CoreClientOption
- func WithCoreClientHTTPClient[T any](httpClient *http.Client) CoreClientOption[T]
- func WithCoreClientMiddlewares[T any](mws ...Middleware[T]) CoreClientOption[T]
- func WithCoreClientRequestInterceptor[T any](hook RequestInterceptorFunc) CoreClientOption[T]
- func WithCoreClientResponseInterceptor[T any](hook ResponseInterceptorFunc) CoreClientOption[T]
- type CoreClientOptionFunc
- type Cursors
- type DebugDetails
- type DebugLogLevel
- type DebugMessage
- type DecodeOptions
- type EncodeResponse
- type FormFile
- type Middleware
- type Options
- type Paging
- type Request
- type RequestForm
- type RequestInterceptor
- type RequestInterceptorFunc
- type RequestOption
- func WithRequestAppSecret[T any](appSecret string) RequestOption[T]
- func WithRequestBearer[T any](bearer string) RequestOption[T]
- func WithRequestBodyReader[T any](bodyReader io.Reader) RequestOption[T]
- func WithRequestDebugLogLevel[T any](level DebugLogLevel) RequestOption[T]
- func WithRequestEndpoints[T any](endpoints ...string) RequestOption[T]
- func WithRequestForm[T any](form *RequestForm) RequestOption[T]
- func WithRequestHeaders[T any](headers map[string]string) RequestOption[T]
- func WithRequestMessage[T any](message *T) RequestOption[T]
- func WithRequestMetadata[T any](metadata types.Metadata) RequestOption[T]
- func WithRequestQueryParams[T any](queryParams map[string]string) RequestOption[T]
- func WithRequestSecured[T any](secured bool) RequestOption[T]
- func WithRequestType[T any](requestType RequestType) RequestOption[T]
- type RequestType
- type ResponseBodyReaderFunc
- type ResponseDecoder
- type ResponseDecoderFunc
- type ResponseError
- type ResponseInterceptor
- type ResponseInterceptorFunc
- type Sender
- type SenderFunc
Examples ¶
Constants ¶
const ( ErrNilResponse = httpError("nil response provided") ErrEmptyResponseBody = httpError("empty response body") ErrNilTarget = httpError("nil value passed for decoding target") ErrRequestFailure = httpError("request failed") ErrDecodeResponseBody = httpError("failed to decode response body") ErrDecodeErrorResponse = httpError("failed to decode error response") )
Variables ¶
This section is empty.
Functions ¶
func DecodeRequestJSON ¶
func DecodeRequestJSON[T any](request *http.Request, v *T, opts DecodeOptions) error
func DecodeResponseJSON ¶
func DecodeResponseJSON[T any](response *http.Response, v *T, opts DecodeOptions) error
func InjectMessageMetadata ¶
func NewRequestWithContext ¶ added in v0.0.9
func NewRequestWithContext[T any](ctx context.Context, method, baseURL string, options ...RequestOption[T], ) (*http.Request, error)
NewRequestWithContext ...
func RequestWithContext ¶
Types ¶
type AnySenderFunc ¶ added in v0.0.13
type AnySenderFunc SenderFunc[any]
type CoreClient ¶
type CoreClient[T any] struct { // contains filtered or unexported fields }
func NewAnySender ¶ added in v0.0.13
func NewAnySender(options ...CoreClientOption[any]) *CoreClient[any]
func NewSender ¶
func NewSender[T any](options ...CoreClientOption[T]) *CoreClient[T]
Example ¶
package main
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"time"
whttp "github.com/piusalfred/whatsapp/pkg/http"
)
type TestMessage struct {
Name string `json:"name"`
Value int `json:"value"`
}
func main() {
customHTTPClient := &http.Client{
Timeout: 2 * time.Second,
}
// Define middleware that logs request information
loggingMiddleware := func(next whttp.SenderFunc[TestMessage]) whttp.SenderFunc[TestMessage] {
return func(ctx context.Context, req *whttp.Request[TestMessage], decoder whttp.ResponseDecoder) error {
fmt.Println("request logger init called before core middlewares")
return next(ctx, req, decoder)
}
}
methodPrinter := func(next whttp.SenderFunc[TestMessage]) whttp.SenderFunc[TestMessage] {
return func(ctx context.Context, req *whttp.Request[TestMessage], decoder whttp.ResponseDecoder) error {
fmt.Printf("from core middleware request method is: %s\n", req.Method)
return next(ctx, req, decoder)
}
}
loggingMiddleware2 := func(next whttp.SenderFunc[TestMessage]) whttp.SenderFunc[TestMessage] {
return func(ctx context.Context, req *whttp.Request[TestMessage], decoder whttp.ResponseDecoder) error {
fmt.Println("called after core middleware request logger final")
return next(ctx, req, decoder)
}
}
loggingMiddleware3 := func(next whttp.SenderFunc[TestMessage]) whttp.SenderFunc[TestMessage] {
return func(ctx context.Context, req *whttp.Request[TestMessage], decoder whttp.ResponseDecoder) error {
err := next(ctx, req, decoder)
fmt.Println("called after request send execution and the err is:", err)
return err
}
}
reqInterceptor := func(_ context.Context, req *http.Request) error {
fmt.Println("Just intercepted the request and the method is:", req.Method)
return nil
}
resInterceptor := func(_ context.Context, res *http.Response) error {
fmt.Println("Just intercepted the response and status code:", res.StatusCode)
return nil
}
resBodyInterceptor := func(_ context.Context, res *http.Response) error {
body, _ := io.ReadAll(res.Body)
defer func() {
res.Body = io.NopCloser(bytes.NewReader(body))
}()
fmt.Println("from response body interceptor:", string(body))
return nil
}
options := []whttp.CoreClientOption[TestMessage]{
whttp.WithCoreClientHTTPClient[TestMessage](customHTTPClient),
whttp.WithCoreClientMiddlewares[TestMessage](methodPrinter),
whttp.WithCoreClientRequestInterceptor[TestMessage](nil),
whttp.WithCoreClientResponseInterceptor[TestMessage](resBodyInterceptor),
}
sender := whttp.NewSender(
options...,
)
longLiveClient := &http.Client{Timeout: time.Hour}
sender.PrependMiddlewares(loggingMiddleware) // they will be executed first before previous set middlewares if any
sender.AppendMiddlewares(loggingMiddleware2, loggingMiddleware3)
sender.SetHTTPClient(longLiveClient)
sender.SetRequestInterceptor(reqInterceptor) // overrides the default interceptors
sender.SetResponseInterceptor(resInterceptor) // overrides the default interceptors
echoHandler := func(w http.ResponseWriter, r *http.Request) {
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "could not read body", http.StatusInternalServerError)
return
}
defer r.Body.Close()
w.WriteHeader(http.StatusOK)
w.Write(bodyBytes)
}
server := httptest.NewServer(http.HandlerFunc(echoHandler))
defer server.Close()
req := &whttp.Request[TestMessage]{
Method: http.MethodPost,
BaseURL: server.URL,
Endpoints: []string{"send"},
Message: &TestMessage{Name: "Hello", Value: 123},
Bearer: "example-token",
}
// Response decoder to handle the response
decoder := whttp.ResponseDecoderJSON(&TestMessage{}, whttp.DecodeOptions{})
// Send the request using the sender
err := sender.Send(context.Background(), req, decoder)
if err != nil {
fmt.Println("Error sending request:", err)
}
}
Output: request logger init called before core middlewares from core middleware request method is: POST called after core middleware request logger final Just intercepted the request and the method is: POST Just intercepted the response and status code: 200 called after request send execution and the err is: <nil>
func (*CoreClient[T]) AppendMiddlewares ¶
func (core *CoreClient[T]) AppendMiddlewares(mws ...Middleware[T])
func (*CoreClient[T]) PrependMiddlewares ¶
func (core *CoreClient[T]) PrependMiddlewares(mws ...Middleware[T])
func (*CoreClient[T]) Send ¶
func (core *CoreClient[T]) Send(ctx context.Context, request *Request[T], decoder ResponseDecoder) error
func (*CoreClient[T]) SetBaseSender ¶ added in v0.0.4
func (core *CoreClient[T]) SetBaseSender(sender Sender[T])
func (*CoreClient[T]) SetHTTPClient ¶
func (core *CoreClient[T]) SetHTTPClient(httpClient *http.Client)
func (*CoreClient[T]) SetRequestInterceptor ¶
func (core *CoreClient[T]) SetRequestInterceptor(hook RequestInterceptorFunc)
func (*CoreClient[T]) SetResponseInterceptor ¶
func (core *CoreClient[T]) SetResponseInterceptor(hook ResponseInterceptorFunc)
type CoreClientOption ¶
type CoreClientOption[T any] interface { // contains filtered or unexported methods }
func WithCoreClientMiddlewares ¶
func WithCoreClientMiddlewares[T any](mws ...Middleware[T]) CoreClientOption[T]
func WithCoreClientRequestInterceptor ¶
func WithCoreClientRequestInterceptor[T any](hook RequestInterceptorFunc) CoreClientOption[T]
func WithCoreClientResponseInterceptor ¶
func WithCoreClientResponseInterceptor[T any](hook ResponseInterceptorFunc) CoreClientOption[T]
type CoreClientOptionFunc ¶ added in v0.0.50
type CoreClientOptionFunc[T any] func(client *CoreClient[T])
type DebugDetails ¶ added in v0.0.50
type DebugDetails struct {
Messages []DebugMessage `json:"messages,omitempty"`
}
type DebugLogLevel ¶ added in v0.0.50
type DebugLogLevel string
const ( DebugLogLevelInfo DebugLogLevel = "info" DebugLogLevelAll DebugLogLevel = "all" DebugLogLevelWarning DebugLogLevel = "warning" DebugLogLevelNone DebugLogLevel = "none" )
func ParseDebugLogLevel ¶ added in v0.0.50
func ParseDebugLogLevel(level string) DebugLogLevel
ParseDebugLogLevel parses the debug log level from a string.
type DebugMessage ¶ added in v0.0.50
type DecodeOptions ¶
type EncodeResponse ¶
func EncodePayload ¶
func EncodePayload(payload any) (*EncodeResponse, error)
EncodePayload takes different types of payloads (form data, readers, JSON) and returns an EncodeResponse.
type Middleware ¶
type Middleware[T any] func(next SenderFunc[T]) SenderFunc[T]
type Options ¶ added in v0.0.50
type Options struct {
HTTPClient *http.Client
RequestHook RequestInterceptorFunc
ResponseHook ResponseInterceptorFunc
}
type Request ¶
type Request[T any] struct { Type RequestType Method string Bearer string Headers map[string]string QueryParams map[string]string BaseURL string Endpoints []string Metadata types.Metadata Message *T Form *RequestForm AppSecret string SecureRequests bool DownloadURL string // this is used for downloading media (it is taken as is) BodyReader io.Reader // contains filtered or unexported fields }
func MakeDownloadRequest ¶ added in v0.0.30
MakeDownloadRequest creates a new request for downloading media.
func MakeRequest ¶ added in v0.0.9
MakeRequest creates a new request with the provided options.
func (*Request[T]) SetDebugLogLevel ¶ added in v0.0.50
func (request *Request[T]) SetDebugLogLevel(level DebugLogLevel)
SetDebugLogLevel sets the debug log level for the request.
func (*Request[T]) SetEndpoints ¶ added in v0.0.33
func (*Request[T]) SetRequestMessage ¶ added in v0.0.33
func (request *Request[T]) SetRequestMessage(message *T)
SetRequestMessage sets the body of the request.
type RequestForm ¶
type RequestInterceptor ¶
type RequestInterceptorFunc ¶
func (RequestInterceptorFunc) InterceptRequest ¶
type RequestOption ¶ added in v0.0.9
func WithRequestAppSecret ¶ added in v0.0.9
WithRequestAppSecret sets the app secret for the request and turns on secure requests.
func WithRequestBearer ¶ added in v0.0.9
WithRequestBearer sets the bearer token for the request.
func WithRequestBodyReader ¶ added in v0.0.31
func WithRequestDebugLogLevel ¶ added in v0.0.50
func WithRequestDebugLogLevel[T any](level DebugLogLevel) RequestOption[T]
func WithRequestEndpoints ¶ added in v0.0.9
WithRequestEndpoints sets the endpoints for the request.
func WithRequestForm ¶ added in v0.0.9
func WithRequestForm[T any](form *RequestForm) RequestOption[T]
func WithRequestHeaders ¶ added in v0.0.9
WithRequestHeaders sets the headers for the request.
func WithRequestMessage ¶ added in v0.0.9
func WithRequestMessage[T any](message *T) RequestOption[T]
WithRequestMessage sets the message for the request.
func WithRequestMetadata ¶ added in v0.0.9
WithRequestMetadata sets the metadata for the request.
func WithRequestQueryParams ¶ added in v0.0.9
WithRequestQueryParams sets the query parameters for the request.
func WithRequestSecured ¶ added in v0.0.9
WithRequestSecured sets the request to be secure.
func WithRequestType ¶ added in v0.0.9
func WithRequestType[T any](requestType RequestType) RequestOption[T]
WithRequestType sets the request type for the request.
type RequestType ¶
type RequestType uint8
const ( RequestTypeSendMessage RequestType = iota RequestTypeUpdateStatus RequestTypeCreateQR RequestTypeListQR RequestTypeGetQR RequestTypeUpdateQR RequestTypeDeleteQR RequestTypeListPhoneNumbers RequestTypeGetPhoneNumber RequestTypeDownloadMedia RequestTypeUploadMedia RequestTypeDeleteMedia RequestTypeGetMedia RequestTypeUpdateBusinessProfile RequestTypeGetBusinessProfile RequestTypeRetrieveFlows RequestTypeRetrieveFlowDetails RequestTypeRetrieveAssets RequestTypePublishFlow RequestTypeDeprecateFlow RequestTypeDeleteFlow RequestTypeUpdateFlow RequestTypeCreateFlow RequestTypeRetrieveFlowPreview RequestTypeGetFlowMetrics RequestTypeInstallApp RequestTypeRefreshToken RequestTypeGenerateToken RequestTypeRevokeToken RequestTypeTwoStepVerification RequestTypeFetchMessagingAnalytics RequestTypeFetchTemplateAnalytics RequestTypeFetchPricingAnalytics RequestTypeFetchConversationAnalytics RequestTypeEnableTemplatesAnalytics RequestTypeDisableButtonClickTracking RequestTypeBlockUsers RequestTypeUnblockUsers RequestTypeListBlockedUsers RequestTypeDisableWelcomeMessage RequestTypeEnableWelcomeMessage RequestTypeGetConversationAutomationComponents RequestTypeUpdateConversationAutomationComponents RequestTypeInitResumableUploadSession RequestTypeGetResumableUploadSessionStatus RequestTypePerformResumableUpload RequestTypeSetWABAAlternateCallbackURI RequestTypeGetWABAAlternateCallbackURI RequestTypeDeleteWABAAlternateCallbackURI RequestTypeSetPhoneNumberAlternateCallbackURI RequestTypeGetPhoneNumberAlternateCallbackURI RequestTypeDeletePhoneNumberAlternateCallbackURI RequestTypeGetSettings RequestTypeUpdateSettings RequestTypeUpdateCallStatus // Create and delete group // Groups with join requests enabled // Get and reset group invite link // Send group invite link template message // Remove group participants // Get group info // Get active groups // Update group settings RequestTypeCreateGroup RequestTypeDeleteGroup RequestTypeGetGroupInviteLink RequestTypeResetGroupInviteLink RequestTypeSendGroupInviteLinkTemplateMessage RequestTypeRemoveGroupParticipants RequestTypeGetGroupInfo RequestTypeGetActiveGroups RequestTypeUpdateGroupSettings RequestTypeUpdateGroupCallStatus )
func (RequestType) Name ¶ added in v0.0.23
func (r RequestType) Name() string
func (RequestType) String ¶ added in v0.0.12
func (r RequestType) String() string
String returns the string representation of the request type.
type ResponseBodyReaderFunc ¶
type ResponseDecoder ¶
type ResponseDecoderFunc ¶
func BodyReaderResponseDecoder ¶
func BodyReaderResponseDecoder(fn ResponseBodyReaderFunc) ResponseDecoderFunc
func ResponseDecoderJSON ¶
func ResponseDecoderJSON[T any](v *T, options DecodeOptions) ResponseDecoderFunc
type ResponseError ¶
type ResponseError struct {
Code int `json:"code,omitempty"`
Err *werrors.Error `json:"error,omitempty"`
}
func (*ResponseError) Error ¶
func (e *ResponseError) Error() string
func (*ResponseError) Unwrap ¶
func (e *ResponseError) Unwrap() error
type ResponseInterceptor ¶
type ResponseInterceptorFunc ¶
func (ResponseInterceptorFunc) InterceptResponse ¶
type SenderFunc ¶
type SenderFunc[T any] func(ctx context.Context, request *Request[T], decoder ResponseDecoder) error
func SendFuncWithInterceptors ¶ added in v0.0.4
func SendFuncWithInterceptors[T any](client *http.Client, reqHook RequestInterceptorFunc, resHook ResponseInterceptorFunc, ) SenderFunc[T]