{"modulePath":"github.com/chrismckee/go-githubapp","version":"v0.0.0-20250623135355-3de399b8f655","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package githubapp\n\nPackage githubapp implements an http.Handler for GitHub events and provides utilities for building GitHub applications. Most users will create implementations of githubapp.EventHandler to handle different webhook event types and register them with the event dispatcher.\n\nMany functions are instrumented with optional logging and metrics collection. The package also defines functions to create authenticated GitHub clients and manage application installations.\n\n## Constants\n\n```go\nconst (\n\tLogKeyEventType       string = \"github_event_type\"\n\tLogKeyDeliveryID      string = \"github_delivery_id\"\n\tLogKeyRepositoryName  string = \"github_repository_name\"\n\tLogKeyRepositoryOwner string = \"github_repository_owner\"\n\tLogKeyPRNum           string = \"github_pr_num\"\n\tLogKeyInstallationID  string = \"github_installation_id\"\n)\n```\n\n```go\nconst (\n\tMetricsKeyRequests    = \"github.requests\"\n\tMetricsKeyRequests2xx = \"github.requests.2xx\"\n\tMetricsKeyRequests3xx = \"github.requests.3xx\"\n\tMetricsKeyRequests4xx = \"github.requests.4xx\"\n\tMetricsKeyRequests5xx = \"github.requests.5xx\"\n\n\tMetricsKeyRequestsCached = \"github.requests.cached\"\n\n\tMetricsKeyRateLimit          = \"github.rate.limit\"\n\tMetricsKeyRateLimitRemaining = \"github.rate.remaining\"\n\tMetricsKeyRateLimitUsed      = \"github.rate.used\"\n\tMetricsKeyRateLimitReset     = \"github.rate.reset\"\n)\n```\n\n```go\nconst (\n\tMetricsKeyQueueLength   = \"github.event.queued\"\n\tMetricsKeyActiveWorkers = \"github.event.workers\"\n\tMetricsKeyEventAge      = \"github.event.age\"\n\tMetricsKeyDroppedEvents = \"github.event.dropped\"\n)\n```\n\n```go\nconst (\n\tDefaultCachingClientCapacity = 64\n)\n```\n\n```go\nconst (\n\tDefaultWebhookRoute string = \"/api/github/hook\"\n)\n```\n\n```go\nconst (\n\tMetricsKeyHandlerError = \"github.handler.error\"\n)\n```\n\n## Variables\n\n```go\nvar (\n\tErrCapacityExceeded = errors.New(\"scheduler: capacity exceeded\")\n)\n```\n\n```go\nvar (\n\t// HandlerRecoverStackDepth is the max depth of stack trace to recover on a\n\t// handler panic.\n\tHandlerRecoverStackDepth = 32\n)\n```\n\n## Functions\n\n```go\nfunc DefaultAsyncErrorCallback(ctx context.Context, d Dispatch, err error)\n```\nDefaultAsyncErrorCallback logs errors.\n\n```go\nfunc DefaultErrorCallback(w http.ResponseWriter, r *http.Request, err error)\n```\nDefaultErrorCallback logs errors and responds with an appropriate status code.\n\n```go\nfunc DefaultResponseCallback(w http.ResponseWriter, r *http.Request, event string, handled bool)\n```\nDefaultResponseCallback responds with a 200 OK for handled events and a 202 Accepted status for all other events. By default, responses are empty. Event handlers may send custom responses by calling the SetResponder function before returning.\n\n```go\nfunc GetInstallationIDFromEvent(event InstallationSource) int64\n```\nGetInstallationIDFromEvent returns the installation ID from a GitHub webhook event payload.\n\n```go\nfunc GetResponder(ctx context.Context) func(http.ResponseWriter, *http.Request)\n```\nGetResponder returns the response function that was set by an event handler. If no response function exists, it returns nil. There is usually no reason to call this outside of a response callback implementation.\n\n```go\nfunc InitializeResponder(ctx context.Context) context.Context\n```\nInitializeResponder prepares the context to work with SetResponder and GetResponder. It is used to test handlers that call SetResponder or to implement custom event dispatchers that support responders.\n\n```go\nfunc NewDefaultEventDispatcher(c Config, handlers ...EventHandler) http.Handler\n```\nNewDefaultEventDispatcher is a convenience method to create an event dispatcher from configuration using the default error and response callbacks.\n\n```go\nfunc NewEventDispatcher(handlers []EventHandler, secret string, opts ...DispatcherOption) http.Handler\n```\nNewEventDispatcher creates an http.Handler that dispatches GitHub webhook requests to the appropriate event handlers. It validates payload integrity using the given secret value.\n\nResponses are controlled by optional error and response callbacks. If these options are not provided, default callbacks are used.\n\n```go\nfunc PreparePRContext(ctx context.Context, installationID int64, repo *github.Repository, number int) (context.Context, zerolog.Logger)\n```\nPreparePRContext adds information about a pull request to the logger in a context and returns the modified context and logger.\n\n```go\nfunc PrepareRepoContext(ctx context.Context, installationID int64, repo *github.Repository) (context.Context, zerolog.Logger)\n```\nPrepareRepoContext adds information about a repository to the logger in a context and returns the modified context and logger.\n\n```go\nfunc SetResponder(ctx context.Context, responder func(http.ResponseWriter, *http.Request))\n```\nSetResponder sets a function that sends a response to GitHub after event processing completes. The context must be initialized by InitializeResponder. The event dispatcher does this automatically before calling a handler.\n\nCustomizing individual handler responses should be rare. Applications that want to modify the standard responses should consider registering a response callback before using this function.\n\n## Types\n\n```go\ntype AsyncErrorCallback func(ctx context.Context, d Dispatch, err error)\n```\nAsyncErrorCallback is called by an asynchronous scheduler when an event handler returns an error or panics. The error from the handler is passed directly as the final argument.\n\nIf the handler panics, err will be a HandlerPanicError.\n\n```go\nfunc MetricsAsyncErrorCallback(reg metrics.Registry) AsyncErrorCallback\n```\nMetricsAsyncErrorCallback logs errors and increments an error counter.\n\n```go\ntype ClientCreator interface {\n\t// NewAppClient returns a new github.Client that performs app authentication for\n\t// the GitHub app with a specific integration ID and private key. The returned\n\t// client makes all calls using the application's authorization token. The\n\t// client gets that token by creating and signing a JWT for the application and\n\t// requesting a token using it. The token is cached by the client and is\n\t// refreshed as needed if it expires.\n\t//\n\t// Used for performing app-level operations that are not associated with a\n\t// specific installation.\n\t//\n\t// See the following for more information:\n\t//  * https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app\n\t//\n\t// Authenticating as a GitHub App lets you do a couple of things:\n\t//  * You can retrieve high-level management information about your GitHub App.\n\t//  * You can request access tokens for an installation of the app.\n\t//\n\t// Tips for determining the arguments for this function:\n\t//  * the integration ID is listed as \"ID\" in the \"About\" section of the app's page\n\t//  * the key bytes must be a PEM-encoded PKCS1 or PKCS8 private key for the application\n\tNewAppClient() (*github.Client, error)\n\n\t// NewAppV4Client returns an app-authenticated v4 API client, similar to NewAppClient.\n\tNewAppV4Client() (*githubv4.Client, error)\n\n\t// NewInstallationClient returns a new github.Client that performs app\n\t// authentication for the GitHub app with the a specific integration ID, private\n\t// key, and the given installation ID. The returned client makes all calls using\n\t// the application's authorization token. The client gets that token by creating\n\t// and signing a JWT for the application and requesting a token using it. The\n\t// token is cached by the client and is refreshed as needed if it expires.\n\t//\n\t// See the following for more information:\n\t//  * https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation\n\t//\n\t// Authenticating as an installation of a Github App lets you perform the following:\n\t//  * https://developer.github.com/v3/apps/available-endpoints/\n\t//\n\t// Tips for determining the arguments for this function:\n\t//  * the integration ID is listed as \"ID\" in the \"About\" section of the app's page\n\t//  * the installation ID is the ID that is shown in the URL of https://{githubURL}/settings/installations/{#}\n\t//      (navigate to the \"installations\" page without the # and go to the app's page to see the number)\n\t//  * the key bytes must be a PEM-encoded PKCS1 or PKCS8 private key for the application\n\tNewInstallationClient(installationID int64) (*github.Client, error)\n\n\t// NewInstallationV4Client returns an installation-authenticated v4 API client, similar to NewInstallationClient.\n\tNewInstallationV4Client(installationID int64) (*githubv4.Client, error)\n\n\t// NewTokenSourceClient returns a *github.Client that uses the passed in OAuth token source for authentication.\n\tNewTokenSourceClient(ts oauth2.TokenSource) (*github.Client, error)\n\n\t// NewTokenSourceClient returns a *githubv4.Client that uses the passed in OAuth token source for authentication.\n\tNewTokenSourceV4Client(ts oauth2.TokenSource) (*githubv4.Client, error)\n\n\t// NewTokenClient returns a *github.Client that uses the passed in OAuth token for authentication.\n\tNewTokenClient(token string) (*github.Client, error)\n\n\t// NewTokenV4Client returns a *githubv4.Client that uses the passed in OAuth token for authentication.\n\tNewTokenV4Client(token string) (*githubv4.Client, error)\n}\n```\n\n```go\nfunc NewCachingClientCreator(delegate ClientCreator, capacity int) (ClientCreator, error)\n```\nNewCachingClientCreator returns a ClientCreator that creates a GitHub client for installations of the app specified by the provided arguments. It uses an LRU cache of the provided capacity to store clients created for installations and returns cached clients when a cache hit exists.\n\n```go\nfunc NewClientCreator(v3BaseURL, v4BaseURL string, integrationID int64, privKeyBytes []byte, opts ...ClientOption) ClientCreator\n```\nNewClientCreator returns a ClientCreator that creates a GitHub client for installations of the app specified by the provided arguments.\n\n```go\nfunc NewDefaultCachingClientCreator(c Config, opts ...ClientOption) (ClientCreator, error)\n```\nNewDefaultCachingClientCreator returns a ClientCreator using values from the configuration or other defaults.\n\n```go\ntype ClientLoggingOption func(*clientLoggingOptions)\n```\nClientLoggingOption controls behavior of client request logs.\n\n```go\nfunc LogRateLimitInformation(options *RateLimitLoggingOption) ClientLoggingOption\n```\nLogRateLimitInformation defines which rate limit information like the number of requests remaining in the current rate limit window is getting logged.\n\n```go\nfunc LogRequestBody(patterns ...string) ClientLoggingOption\n```\nLogRequestBody enables request body logging for requests to paths matching any of the regular expressions in patterns. It panics if any of the patterns is not a valid regular expression.\n\n```go\nfunc LogResponseBody(patterns ...string) ClientLoggingOption\n```\nLogResponseBody enables response body logging for requests to paths matching any of the regular expressions in patterns. It panics if any of the patterns is not a valid regular expression.\n\n```go\ntype ClientMiddleware func(http.RoundTripper) http.RoundTripper\n```\nClientMiddleware modifies the transport of a GitHub client to add common functionality, like logging or metrics collection.\n\n```go\nfunc ClientLogging(lvl zerolog.Level, opts ...ClientLoggingOption) ClientMiddleware\n```\nClientLogging creates client middleware that logs request and response information at the given level. If the request fails without creating a response, it is logged with a status code of -1. The middleware uses a logger from the request context.\n\n```go\nfunc ClientMetrics(registry metrics.Registry) ClientMiddleware\n```\nClientMetrics creates client middleware that records metrics about all requests. It also defines the metrics in the provided registry.\n\n```go\ntype ClientOption func(c *clientCreator)\n```\n\n```go\nfunc WithClientCaching(alwaysValidate bool, cache func() httpcache.Cache) ClientOption\n```\nWithClientCaching sets an HTTP cache for all created clients using the provided cache implementation If alwaysValidate is true, the cache validates all saved responses before returning them. Otherwise, it respects the caching headers returned by GitHub. [https://developer.github.com/v3/#conditional-requests](https://developer.github.com/v3/#conditional-requests)\n\n```go\nfunc WithClientMiddleware(middleware ...ClientMiddleware) ClientOption\n```\nWithClientMiddleware adds middleware that is applied to all created clients.\n\n```go\nfunc WithClientTimeout(timeout time.Duration) ClientOption\n```\nWithClientTimeout sets a request timeout for requests made by all created clients.\n\n```go\nfunc WithClientUserAgent(agent string) ClientOption\n```\nWithClientUserAgent sets the base user agent for all created clients.\n\n```go\nfunc WithTransport(transport http.RoundTripper) ClientOption\n```\nWithTransport sets the http.RoundTripper used to make requests. Clients can provide an http.Transport instance to modify TLS, proxy, or timeout options. By default, clients use http.DefaultTransport.\n\n```go\ntype Config struct {\n\tWebURL   string `yaml:\"web_url\" json:\"webUrl\"`\n\tV3APIURL string `yaml:\"v3_api_url\" json:\"v3ApiUrl\"`\n\tV4APIURL string `yaml:\"v4_api_url\" json:\"v4ApiUrl\"`\n\n\tApp struct {\n\t\tIntegrationID int64  `yaml:\"integration_id\" json:\"integrationId\"`\n\t\tWebhookSecret string `yaml:\"webhook_secret\" json:\"webhookSecret\"`\n\t\tPrivateKey    string `yaml:\"private_key\" json:\"privateKey\"`\n\t} `yaml:\"app\" json:\"app\"`\n\n\tOAuth struct {\n\t\tClientID     string `yaml:\"client_id\" json:\"clientId\"`\n\t\tClientSecret string `yaml:\"client_secret\" json:\"clientSecret\"`\n\t} `yaml:\"oauth\" json:\"oauth\"`\n}\n```\n\n```go\nfunc (c *Config) SetValuesFromEnv(prefix string)\n```\nSetValuesFromEnv sets values in the configuration from coresponding environment variables, if they exist. The optional prefix is added to the start of the environment variable names.\n\n```go\ntype Dispatch struct {\n\tHandler EventHandler\n\n\tEventType  string\n\tDeliveryID string\n\tPayload    []byte\n}\n```\nDispatch is a webhook payload and the handler that handles it.\n\n```go\nfunc (d Dispatch) Execute(ctx context.Context) error\n```\nExecute calls the Dispatch's handler with the stored arguments.\n\n```go\ntype DispatcherOption func(*eventDispatcher)\n```\nDispatcherOption configures properties of an event dispatcher.\n\n```go\nfunc WithErrorCallback(onError ErrorCallback) DispatcherOption\n```\nWithErrorCallback sets the error callback for a dispatcher.\n\n```go\nfunc WithResponseCallback(onResponse ResponseCallback) DispatcherOption\n```\nWithResponseCallback sets the response callback for an event dispatcher.\n\n```go\nfunc WithScheduler(s Scheduler) DispatcherOption\n```\nWithScheduler sets the scheduler used to process events. Setting a non-default scheduler can enable asynchronous processing. When a scheduler is asynchronous, the dispatcher validatates event payloads, queues valid events for handling, and then responds to GitHub without waiting for the handler to complete.  This is useful when handlers may take longer than GitHub's timeout for webhook deliveries.\n\n```go\ntype ErrorCallback func(w http.ResponseWriter, r *http.Request, err error)\n```\nErrorCallback is called when an event handler returns an error. The error from the handler is passed directly as the final argument.\n\n```go\nfunc MetricsErrorCallback(reg metrics.Registry) ErrorCallback\n```\nMetricsErrorCallback logs errors, increments an error counter, and responds with an appropriate status code.\n\n```go\ntype EventHandler interface {\n\t// Handles returns a list of GitHub events that this handler handles\n\t// See https://developer.github.com/v3/activity/events/types/\n\tHandles() []string\n\n\t// Handle processes the GitHub event \"eventType\" with the given delivery ID\n\t// and payload. The EventDispatcher guarantees that the Handle method will\n\t// only be called for the events returned by Handles().\n\t//\n\t// If Handle returns an error, processing stops and the error is passed\n\t// directly to the configured error handler.\n\tHandle(ctx context.Context, eventType, deliveryID string, payload []byte) error\n}\n```\n\n```go\ntype HandlerPanicError struct {\n\t// contains filtered or unexported fields\n}\n```\nHandlerPanicError is an error created from a recovered handler panic.\n\n```go\nfunc (e HandlerPanicError) Error() string\n```\n\n```go\nfunc (e HandlerPanicError) Format(s fmt.State, verb rune)\n```\nFormat formats the error optionally including the stack trace.\n\n\t%s    the error message\n\t%v    the error message and the source file and line number for each stack frame\n\nFormat accepts the following flags:\n\n\t%+v   the error message and the function, file, and line for each stack frame\n\n```go\nfunc (e HandlerPanicError) StackTrace() []runtime.Frame\n```\nStackTrace returns the stack of the panicking goroutine.\n\n```go\nfunc (e HandlerPanicError) Value() interface{}\n```\nValue returns the exact value with which panic() was called.\n\n```go\ntype Installation struct {\n\tID      int64\n\tOwner   string\n\tOwnerID int64\n}\n```\nInstallation is a minimal representation of a GitHub app installation.\n\n```go\ntype InstallationNotFound string\n```\nInstallationNotFound is returned when no installation exists for a specific owner or repository.\n\n```go\nfunc (err InstallationNotFound) Error() string\n```\n\n```go\ntype InstallationSource interface {\n\tGetInstallation() *github.Installation\n}\n```\nInstallationSource is implemented by GitHub webhook event payload types.\n\n```go\ntype InstallationsService interface {\n\t// ListAll returns all installations for this app.\n\tListAll(ctx context.Context) ([]Installation, error)\n\n\t// GetByOwner returns the installation for an owner (user or organization).\n\t// It returns an InstallationNotFound error if no installation exists for\n\t// the owner.\n\tGetByOwner(ctx context.Context, owner string) (Installation, error)\n\n\t// GetByRepository returns the installation for a repository.\n\t// It returns an InstallationNotFound error if no installation exists for\n\t// the repository.\n\tGetByRepository(ctx context.Context, owner string, repo string) (Installation, error)\n}\n```\nInstallationsService retrieves installation information for a given app. Implementations may chose how to retrieve, store, or cache these values.\n\nThis service is useful for background processes that do not respond directly to webhooks, since webhooks provide installation IDs in their payloads.\n\n```go\nfunc NewCachingInstallationsService(delegate InstallationsService, expiry, cleanup time.Duration) InstallationsService\n```\nNewCachingInstallationsService returns an InstallationsService that always queries GitHub. It should be created with a client that authenticates as the target. It uses a time based cache of the provided expiry/cleanup time to store app installation info for repositories or owners and returns the cached installation info when a cache hit exists.\n\n```go\nfunc NewInstallationsService(appClient *github.Client) InstallationsService\n```\nNewInstallationsService returns an InstallationsService that always queries GitHub. It should be created with a client that authenticates as the target application.\n\n```go\ntype RateLimitLoggingOption struct {\n\tLimit     bool\n\tRemaining bool\n\tUsed      bool\n\tReset     bool\n\tResource  bool\n}\n```\nRateLimitLoggingOption controls which rate limit information is logged.\n\n```go\ntype ResponseCallback func(w http.ResponseWriter, r *http.Request, event string, handled bool)\n```\nResponseCallback is called to send a response to GitHub after an event is handled. It is passed the event type and a flag indicating if an event handler was called for the event.\n\n```go\ntype Scheduler interface {\n\tSchedule(ctx context.Context, d Dispatch) error\n}\n```\nScheduler is a strategy for executing event handlers.\n\nThe Schedule method takes a Dispatch and executes it by calling the handler for the payload. The execution may be asynchronous, but the scheduler must create a new context in this case. The dispatcher waits for Schedule to return before responding to GitHub, so asynchronous schedulers should only return errors that happen during scheduling, not during execution.\n\nSchedule may return ErrCapacityExceeded if it cannot schedule or queue new events at the time of the call.\n\n```go\nfunc AsyncScheduler(opts ...SchedulerOption) Scheduler\n```\nAsyncScheduler returns a scheduler that executes handlers in new goroutines. Goroutines are not reused and there is no limit on the number created.\n\n```go\nfunc DefaultScheduler() Scheduler\n```\nDefaultScheduler returns a scheduler that executes handlers in the go routine of the caller and returns any error.\n\n```go\nfunc QueueAsyncScheduler(queueSize int, workers int, opts ...SchedulerOption) Scheduler\n```\nQueueAsyncScheduler returns a scheduler that executes handlers in a fixed number of worker goroutines. If no workers are available, events queue until the queue is full.\n\n```go\ntype SchedulerOption func(*scheduler)\n```\nSchedulerOption configures properties of a scheduler.\n\n```go\nfunc WithAsyncErrorCallback(onError AsyncErrorCallback) SchedulerOption\n```\nWithAsyncErrorCallback sets the error callback for an asynchronous scheduler. If not set, the scheduler uses DefaultAsyncErrorCallback.\n\n```go\nfunc WithSchedulingMetrics(r metrics.Registry) SchedulerOption\n```\nWithSchedulingMetrics enables metrics reporting for schedulers.\n\n```go\ntype ValidationError struct {\n\tEventType  string\n\tDeliveryID string\n\tCause      error\n}\n```\nValidationError is passed to error callbacks when the webhook payload fails validation.\n\n```go\nfunc (ve ValidationError) Error() string\n```\n\n","path":"github.com/chrismckee/go-githubapp/githubapp","name":"githubapp","synopsis":"Package githubapp implements an http.Handler for GitHub events and provides utilities for building GitHub applications.","isRedistributable":true}
