Documentation
¶
Overview ¶
Package webhook sends webhooks: HTTP requests a mock makes after it replies. A WebHook is an on_complete listener: register it under the name mocks give, as with mockhttp.Setup().OnCompleteListener("webhook", wh). The vlatte command registers one as webhook. Its parameters are Args, or a map as mock files write them: see ArgsFromMap.
Example ¶
package main
import (
"fmt"
"net/http"
"github.com/caffeine-projects/vlatte/match"
"github.com/caffeine-projects/vlatte/mockhttp"
"github.com/caffeine-projects/vlatte/webhook"
)
func main() {
// The service the webhook calls.
target := mockhttp.MustNew(mockhttp.Setup().Silent())
target.MustStart()
defer target.Close()
hook := target.MustMock(mockhttp.Postf("/hooks/orders").
Body(match.Equal("order 42 shipped")).
Reply(mockhttp.NoContent()))
wh, err := webhook.New()
if err != nil {
panic(err)
}
// The server registers the webhook as an on-complete listener by name; a mock names it to send it.
m := mockhttp.MustNew(mockhttp.Setup().Silent().OnCompleteListener("webhook", wh))
m.MustStart()
defer m.Close()
m.MustMock(mockhttp.Putf("/orders/42/ship").
OnCompleteEvent(webhook.Options().
Method(http.MethodPost).
URL(target.URL("/hooks/orders")).
BodyTemplate("order {{ index .Request.URLPathSegments 1 }} shipped").
Build("webhook")).
Reply(mockhttp.OK()))
req, err := http.NewRequest(http.MethodPut, m.URL("/orders/42/ship"), nil)
if err != nil {
panic(err)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
res.Body.Close()
// The response waits for the webhook, so the target has it once the call returns.
fmt.Println(res.StatusCode, hook.Hits())
}
Output: 200 1
Index ¶
- Variables
- type Args
- type ArgsBuilder
- func (b *ArgsBuilder) Body(body string) *ArgsBuilder
- func (b *ArgsBuilder) BodyFile(name string) *ArgsBuilder
- func (b *ArgsBuilder) BodyTemplate(t string) *ArgsBuilder
- func (b *ArgsBuilder) Build(name string) vlatte.EventConfig
- func (b *ArgsBuilder) Delay(d time.Duration) *ArgsBuilder
- func (b *ArgsBuilder) Header(k, v string) *ArgsBuilder
- func (b *ArgsBuilder) HeaderTemplate(k, v string) *ArgsBuilder
- func (b *ArgsBuilder) Method(method string) *ArgsBuilder
- func (b *ArgsBuilder) Multipart(body MultipartBody) *ArgsBuilder
- func (b *ArgsBuilder) Timeout(d time.Duration) *ArgsBuilder
- func (b *ArgsBuilder) URL(u string) *ArgsBuilder
- func (b *ArgsBuilder) URLTemplate(t string) *ArgsBuilder
- type MultipartBody
- type Option
- type Transform
- type WebHook
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrBadArg is the error of [ArgsFromMap], [WebHook.Prepare] and [WebHook.Run] on webhook parameters that are // malformed or conflict, such as a missing url or two bodies. ErrBadArg = errors.New("webhook: bad argument") // ErrRenderingTemplate is the error of a url, body or header template that fails to compile, in // [WebHook.Prepare] or [WebHook.Run], or to execute, in [WebHook.Run]. A multipart template's error doesn't wrap // it. ErrRenderingTemplate = errors.New("webhook: rendering error") )
Functions ¶
This section is empty.
Types ¶
type Args ¶
type Args struct {
URL string
URLTemplate string
Method string
Header http.Header
HeaderTemplate map[string][]string
Body string
BodyTemplate string
BodyFile string
// Multipart is a multipart body, such as one built with mockhttp.MultipartForm. It sets the Content-Type.
Multipart MultipartBody
// Delay is how long the webhook waits, once the mock replied, before it sends the request. The response waits for
// it too, unless the event runs after the response. The timeout counts from the send.
Delay time.Duration
// Timeout limits how long the request may take, from sending it to its answer. It wins over the WebHook's
// WithTimeout. 0 keeps that one, or else 10s.
Timeout time.Duration
// contains filtered or unexported fields
}
Args configures a WebHook HTTP request. It is parsed from the parameters in the event config (e.g. mock definition). URLTemplate, the HeaderTemplate values and BodyTemplate are templates, compiled with the template engine of the server and rendered with the data of the request that completed the mock. A header goes with each of its values, in order. Header names ignore case, so a name is set once, in Header or HeaderTemplate.
func ArgsFromMap ¶
ArgsFromMap decodes the parameters of a webhook event, as a mock file's on_complete writes them:
- url, or url_template, a template: a string;
- method: a string, GET when empty;
- header and header_template, whose values are templates: objects of strings, or of lists of strings for headers with several values;
- one body: body, body_base64, the bytes in standard base64, body_template, a template, or body_file, a string; or multipart, or multipart_template, whose text is templates: an object with the type, boundary, params and parts of the body;
- delay and timeout: milliseconds, or a Go duration such as 1.5s.
As in mock files, each value must have its type, and other keys are errors. The webhook's checks of what a request needs, such as one of url and url_template, come when the mock is built. A map built in code means what its JSON means, so a map[string]string or an int is fine where its JSON is. The error wraps ErrBadArg and lists every problem.
func (*Args) Describe ¶
func (a *Args) Describe() vlatte.Descriptor
Describe implements vlatte.SelfDescriptive: the parameters as a mock file writes them, the ones set only, so the description of a mock, such as the admin API gives, loads back with the same webhook. A relative body file is joined to the mock file's directory, which a description loaded back doesn't have. A body that isn't UTF-8 is described in body_base64. A multipart body is described when it describes itself, as mockhttp's do.
type ArgsBuilder ¶
type ArgsBuilder struct {
// contains filtered or unexported fields
}
ArgsBuilder provides a convenient way to configure a WebHook for a mock.
func Options ¶
func Options() *ArgsBuilder
Options starts an ArgsBuilder to configure a WebHook for a mock.
func (*ArgsBuilder) Body ¶
func (b *ArgsBuilder) Body(body string) *ArgsBuilder
Body sets the HTTP request body of the WebHook.
func (*ArgsBuilder) BodyFile ¶
func (b *ArgsBuilder) BodyFile(name string) *ArgsBuilder
BodyFile sets the file the HTTP request body of the WebHook is read from, each time it is sent. A relative name opens from the working directory.
func (*ArgsBuilder) BodyTemplate ¶
func (b *ArgsBuilder) BodyTemplate(t string) *ArgsBuilder
BodyTemplate sets the HTTP request body of the WebHook as a template, rendered with the request that completed the mock.
func (*ArgsBuilder) Build ¶
func (b *ArgsBuilder) Build(name string) vlatte.EventConfig
Build builds the vlatte.EventConfig required to set up a WebHook for a mock (on-complete event). The config gets a copy of the parameters, so changing the builder afterwards changes only the configs built afterwards.
func (*ArgsBuilder) Delay ¶
func (b *ArgsBuilder) Delay(d time.Duration) *ArgsBuilder
Delay sets how long the WebHook waits, once the mock replied, before it sends the request. The response waits for it too, unless the event runs after the response: see vlatte.EventConfig.AfterResponse.
func (*ArgsBuilder) Header ¶
func (b *ArgsBuilder) Header(k, v string) *ArgsBuilder
Header adds a value of an HTTP header to be sent in the WebHook. A name given again adds another value, sent after the ones before.
func (*ArgsBuilder) HeaderTemplate ¶
func (b *ArgsBuilder) HeaderTemplate(k, v string) *ArgsBuilder
HeaderTemplate adds a value of an HTTP header that is a template, rendered with the request that completed the mock. A name given again adds another value, sent after the ones before.
func (*ArgsBuilder) Method ¶
func (b *ArgsBuilder) Method(method string) *ArgsBuilder
Method sets the HTTP method.
func (*ArgsBuilder) Multipart ¶
func (b *ArgsBuilder) Multipart(body MultipartBody) *ArgsBuilder
Multipart sets a multipart body for the WebHook, such as one built with mockhttp.MultipartForm. For a body whose text is templates, call Template on it: mockhttp.MultipartForm(...).Template().
func (*ArgsBuilder) Timeout ¶
func (b *ArgsBuilder) Timeout(d time.Duration) *ArgsBuilder
Timeout limits how long the request of the WebHook may take, from sending it to its answer. It wins over the listener's webhook.WithTimeout.
func (*ArgsBuilder) URL ¶
func (b *ArgsBuilder) URL(u string) *ArgsBuilder
URL sets the URL of the target service.
func (*ArgsBuilder) URLTemplate ¶
func (b *ArgsBuilder) URLTemplate(t string) *ArgsBuilder
URLTemplate sets the URL of the target service as a template, rendered with the request that completed the mock.
type MultipartBody ¶
type MultipartBody interface {
// Check checks the body and compiles its templates with engine, without writing it.
Check(engine vlatte.TemplateEngine) error
// Encode writes the body, with its templates compiled with engine and rendered with data: the data of the request
// that completed the mock. It returns the body's Content-Type and bytes.
Encode(engine vlatte.TemplateEngine, data any) (contentType string, body []byte, err error)
}
MultipartBody is a multipart body for a webhook, such as one built with mockhttp.MultipartForm.
type Option ¶
Option configures a WebHook in New. An Option that returns an error fails New.
func WithLogger ¶
WithLogger returns an Option that sets the logger of a WebHook's sends and answers. Without it, a WebHook logs with the server's logger, which the event's vlatte.Kit gives, so Setup().Silent() silences webhooks too.
func WithTimeout ¶
WithTimeout returns an Option that limits how long each request of a WebHook may take, from sending it to its answer: the timeout of every webhook it sends, unless a webhook sets its own timeout parameter. 0 is 10 seconds. A negative timeout is an error.
func WithTransform ¶
WithTransform returns an Option that sets the Transform function for a WebHook. The Transform function allows customization of request data before sending.
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"github.com/caffeine-projects/vlatte"
"github.com/caffeine-projects/vlatte/mockhttp"
"github.com/caffeine-projects/vlatte/webhook"
)
func main() {
target := mockhttp.MustNew(mockhttp.Setup().Silent())
target.MustStart()
defer target.Close()
hook := target.MustMock(mockhttp.Postf("/hooks").
Headerf("X-Signature", "signed").
Reply(mockhttp.NoContent()))
// A Transform changes the request of each send, here to add a header the mock doesn't set.
wh, err := webhook.New(webhook.WithTransform(func(_ context.Context, _ vlatte.OnComplete, args *webhook.Args) error {
args.Header.Set("X-Signature", "signed")
return nil
}))
if err != nil {
panic(err)
}
m := mockhttp.MustNew(mockhttp.Setup().Silent().OnCompleteListener("webhook", wh))
m.MustStart()
defer m.Close()
m.MustMock(mockhttp.Getf("/ping").
OnCompleteEvent(webhook.Options().Method(http.MethodPost).URL(target.URL("/hooks")).Build("webhook")).
Reply(mockhttp.OK()))
res, err := http.Get(m.URL("/ping"))
if err != nil {
panic(err)
}
res.Body.Close()
fmt.Println(hook.Hits())
}
Output: 1
func WithTransport ¶
func WithTransport(transport http.RoundTripper) Option
WithTransport returns an Option that sets the http.RoundTripper for a WebHook, in place of the server's, which the event's vlatte.Kit gives.
type Transform ¶
Transform lets users transform and customize the WebHook event args and the Args before they are used. It runs every time WebHook.Run is called.
type WebHook ¶
type WebHook struct {
// contains filtered or unexported fields
}
WebHook is an automated HTTP request sent when an on-complete event is fired. Register it with vlatte.Listener.OnComplete (e.g. via mockhttp.Setup().OnCompleteListener(name, wh)). mockhttp sends it once the mock replied, and the response waits for it: a test checks the target right after. An event set to run after the response doesn't hold it: see vlatte.EventConfig.AfterResponse.
It logs each send and its answer at info level, with WithLogger's logger, or else with the server's, which the event's vlatte.Kit gives. It sends with WithTransport's transport, or else with the server's, from the Kit too: mockhttp gives its Config.Transport, or else one it closes with the server, as mockgrpc does. Relative files, such as a body_file, open from the Kit's Dir: the directory of the mock file. An event without a Kit logs nothing, sends with http.DefaultTransport, and opens files from the working directory. A send fails when the target can't be reached in time, or answers with a status outside 2xx; a redirect isn't followed. A send reads up to 256 KiB of the answer, within its time, so its connection carries the next one. The time is the webhook's own timeout parameter, or else WithTimeout's, the timeout of every webhook the WebHook sends, such as the vlatte command's webhook.timeout setting. Without either, it is 10s. A zero WebHook is ready to use.
func (*WebHook) Prepare ¶
func (w *WebHook) Prepare(cfg vlatte.EventConfig, engine vlatte.TemplateEngine) (vlatte.Parameters, error)
Prepare implements vlatte.EventPreparer. It decodes the parameters of a mock's webhook, checks them, and compiles their templates with the server's engine, so a mistake fails the mock when it is built instead of each send. Run receives the decoded *Args.