{"modulePath":"github.com/patrontech/go-githubapp","version":"v0.0.0-20200318133808-1a2598a630e1","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)\n```\n\n```go\nconst (\n\tDefaultCachingClientCapacity = 64\n)\n```\n\n```go\nconst (\n\tDefaultWebhookRoute string = \"/api/github/hook\"\n)\n```\n\n## Functions\n\n```go\nfunc DefaultErrorCallback(w http.ResponseWriter, r *http.Request, err error)\n```\nDefaultErrorCallback logs errors and responds with a 500 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 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. This function may only be called from event handler functions invoked by the event dispatcher.\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 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// 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 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) 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 WithClientUserAgent(agent string) ClientOption\n```\nWithClientUserAgent sets the base user agent for all created clients.\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 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 an event dispatcher.\n\n```go\nfunc WithResponseCallback(onResponse ResponseCallback) DispatcherOption\n```\nWithResponseCallback sets the response callback for an event dispatcher.\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\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 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```\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 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 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 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/patrontech/go-githubapp/githubapp","name":"githubapp","synopsis":"Package githubapp implements an http.Handler for GitHub events and provides utilities for building GitHub applications.","isRedistributable":true}
