probot

package module
v0.0.0-...-25667b3 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

README

header

go reference go report card license

  • 🔐 Webhook Validation: HMAC signature verification built-in.
  • 🤖 Auth Handling: Auto-refreshing installation tokens via ghinstallation.
  • 🧩 GitHub Client: Pre-authenticated go-github client in every context.
  • 📄 Repo Config: Load .github/config.yml with defaults and inheritance.
  • 🧙 Setup Wizard: One-click GitHub App registration via manifest flow.

Quick Start

go get github.com/light-cms/probot-go

Create main.go:

package main

import (
    "context"
    "os"

    "github.com/google/go-github/github"
    "github.com/light-cms/probot-go"
)

func main() {
    app, err := probot.New(probot.Options{
        AppID:      os.Getenv("APP_ID"),
        PrivateKey: os.Getenv("PRIVATE_KEY"),
        Secret:     os.Getenv("WEBHOOK_SECRET"),
    })
    if err != nil {
        panic(err)
    }

    app.On("issues.opened", func(ctx *probot.Context) error {
        issue := ctx.Issue()
        _, _, err := ctx.GitHub().Issues.CreateComment(
            context.Background(), issue.Owner, issue.Repo, issue.Number,
            &github.IssueComment{Body: github.Ptr("Thanks for opening this issue!")},
        )
        return err
    })

    probot.NewServer(probot.ServerOptions{Probot: app}).Start()
}

Run it:

go run main.go

Visit http://localhost:3000 to register your app via the wizard if no env vars are set.

API Overview

Options

type Options struct {
    AppID        string        // GitHub App ID
    PrivateKey   string        // PEM contents or path via PRIVATE_KEY_PATH
    Secret       string        // Webhook secret (default: "development")
    GithubToken  string        // Optional: Use PAT instead of App Auth
    LogLevel     string        // trace|debug|info|warn|error (default: info)
    Port         int           // Default: 3000
    BaseURL      string        // For GitHub Enterprise Server
}

Event Handling

// Single event
app.On("pull_request.opened", handler)

// Multiple events
app.OnMany([]string{"issues.closed", "pr.closed"}, handler)

// All events
app.OnAny(handler)

// Errors
app.OnError(func(ctx *probot.Context, err error) { ... })

Context Helpers

  • ctx.GitHub(): Authenticated *github.Client.
  • ctx.Issue(), ctx.Repo(), ctx.PullRequest(): Parsed structs.
  • ctx.Config("config.yml", defaults): Loads repo config.
  • ctx.Log(): Structured logger (zerolog).

Embedding in Existing Server

mux := http.NewServeMux()
mux.Handle("/webhooks", app.WebhookMiddleware(http.HandlerFunc(next)))
http.ListenAndServe(":8080", mux)

Testing

Tests run offline. Use Receive to simulate events:

app.Receive(&github.Event{
    Type:       github.String("issues"),
    Action:     github.String("opened"),
    // ... payload
})

Contributing

  1. Fork the repo.
  2. Run go test ./... and gofmt -l ..
  3. Submit a PR.

License

ISC

Documentation

Overview

Package probot is a Go port of Probot, a framework for building GitHub Apps.

It eliminates the boilerplate of webhook validation, authentication and API setup so you can focus on what your app actually does:

app, _ := probot.New(probot.Options{
	AppID:      os.Getenv("APP_ID"),
	PrivateKey: os.Getenv("PRIVATE_KEY"),
	Secret:     os.Getenv("WEBHOOK_SECRET"),
	Webhook: 	os.Getenv("WEBHOOK_URL")
})

app.On("issues.opened", func(ctx *probot.Context) error {
	params := ctx.Issue()
	_, _, err := ctx.GitHub().Issues.CreateComment(ctx,
		params.Owner, params.Repo, params.Number,
		&github.IssueComment{Body: github.Ptr("Thanks for opening this issue!")},
	)
	return err
})

server := probot.NewServer(probot.ServerOptions{Probot: app})
_ = server.Start()

Index

Constants

View Source
const Version = "0.1.0"

Version is the current version of this port.

Variables

This section is empty.

Functions

func Defaults

func Defaults(o Options) func(*Options)

Defaults returns a functional option that pre-applies the given options as defaults. Options passed directly to New still override these. Mirrors Probot.defaults().

func LoadEnvFile

func LoadEnvFile(path string) error

LoadEnvFile parses a .env style file (KEY=VALUE lines, # comments) into the process environment. It does not override variables that are already set.

Values may be bare, single quoted or double quoted. Double quoted values are unescaped, so a PEM private key stored on a single line as "-----BEGIN...\nMIIE...\n-----END...\n" is restored with real newlines — which is how the setup wizard writes PRIVATE_KEY.

func VerifyGitHubSignature

func VerifyGitHubSignature(secret, payload, signature string) error

VerifyGitHubSignature verifies the X-Hub-Signature-256 header against the payload using the given webhook secret. Returns an error when the signature is missing or invalid.

Types

type ApplicationFunc

type ApplicationFunc func(app *Probot, opts ApplicationFunctionOptions) error

ApplicationFunc is a function loaded into a Probot instance via Load. It typically registers webhook handlers.

type ApplicationFunctionOptions

type ApplicationFunctionOptions struct {
	Cwd string
}

ApplicationFunctionOptions are options forwarded to an ApplicationFunc.

type Context

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

Context is passed to every webhook event handler. It wraps the raw GitHub webhook event and provides an authenticated GitHub client, a scoped logger and convenience helpers for extracting repository, issue and pull request parameters.

func (*Context) Config

func (c *Context) Config(fileName string, defaultConfig ...map[string]any) (map[string]any, error)

Config loads a YAML/JSON configuration file from the .github/ directory of the repository's default branch, merging any defaults and honouring the _extends cross-repository key. Returns nil if the file is absent and no defaults were provided.

func (*Context) GitHub

func (c *Context) GitHub() *github.Client

GitHub returns the authenticated go-github client for the triggering installation. Octokit is an alias for the same value, mirroring probot's context.octokit.

func (*Context) ID

func (c *Context) ID() string

ID returns the unique delivery ID GitHub assigned to this webhook delivery.

func (*Context) IsBot

func (c *Context) IsBot() bool

IsBot reports whether the event sender is a GitHub bot. Use it to avoid infinite loops when your app reacts to its own activity.

func (*Context) Issue

func (c *Context) Issue() (IssueParams, error)

Issue returns owner, repo and issue number resolved from the payload.

func (*Context) Log

func (c *Context) Log() zerolog.Logger

Log returns a logger scoped to this event delivery.

func (*Context) Name

func (c *Context) Name() string

Name returns the top-level webhook event name, e.g. "issues" or "push".

func (*Context) Octokit

func (c *Context) Octokit() *github.Client

Octokit is an alias for GitHub(), mirroring probot's context.octokit.

func (*Context) ParseInto

func (c *Context) ParseInto(v any) error

ParseInto unmarshals the webhook payload into a typed struct, e.g.

var ev probe.Github.PushEvent
_ = ctx.ParseInto(&ev)

func (*Context) Payload

func (c *Context) Payload() map[string]any

Payload returns the parsed webhook JSON payload as a map.

func (*Context) PullRequest

func (c *Context) PullRequest() (PullRequestParams, error)

PullRequest returns owner, repo and pull request number resolved from the payload.

func (*Context) Repo

func (c *Context) Repo() (Repo, error)

Repo returns the owner and repo extracted from payload["repository"].

type ErrorHandlerFunc

type ErrorHandlerFunc func(ctx *Context, err error)

ErrorHandlerFunc handles errors raised inside webhook handlers.

type HandlerFunc

type HandlerFunc func(ctx *Context) error

HandlerFunc is a webhook event handler. It receives a *Context and may return an error that will be routed to the registered error handler.

type IssueParams

type IssueParams struct {
	Owner  string
	Repo   string
	Number int
}

IssueParams identifies an issue or pull request for go-github API calls.

type Options

type Options struct {
	// AppID is the numeric ID of the GitHub App. Required unless GithubToken
	// is set.
	AppID string

	// PrivateKey is the full contents of the .pem private key downloaded from
	// your GitHub App's settings page. Required unless GithubToken is set.
	PrivateKey string

	// Secret is the webhook secret used to validate incoming payloads from
	// GitHub. Defaults to "development" when not set.
	Secret string

	// GithubToken is a personal access token or installation token. Use it as
	// an alternative to AppID + PrivateKey for simple single-repository
	// integrations.
	GithubToken string

	// LogLevel sets the minimum log level. One of trace, debug, info, warn,
	// error, fatal, panic. Defaults to "info".
	LogLevel string

	// LogFormat is "pretty" (human readable, default) or "json" (newline
	// delimited JSON).
	LogFormat string

	// Port is the TCP port the HTTP server listens on. Defaults to 3000.
	Port int

	// Host is the hostname or IP the HTTP server binds to. Defaults to
	// "localhost".
	Host string

	// BaseURL overrides the GitHub API base URL, e.g. for GitHub Enterprise
	// Server: "https://github.example.com/api/v3".
	BaseURL string

	// WebhookPath is the URL path the webhook handler is mounted on. Defaults
	// to "/api/github/webhooks".
	WebhookPath string

	// WebhookProxyURL is the URL of a webhook proxy service (e.g. Smee.io)
	// that forwards webhooks to localhost.
	WebhookProxyURL string

	// RequestTimeout limits each GitHub API request. Defaults to 30s.
	RequestTimeout time.Duration
}

Options configures a Probot instance. Either AppID + PrivateKey or GithubToken must be provided; all other options are optional.

func OptionsFromEnv

func OptionsFromEnv() (Options, error)

OptionsFromEnv builds Options from environment variables. It understands the standard names used by probot apps:

APP_ID, PRIVATE_KEY, PRIVATE_KEY_PATH, WEBHOOK_SECRET, GITHUB_TOKEN,
LOG_LEVEL, LOG_FORMAT, PORT, HOST, GHE_HOST, WEBHOOK_PATH

A PROBOT_ prefix is accepted as an alternative for every variable (e.g. PROBOT_APP_ID).

type Probot

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

Probot is the core framework. It manages authentication, webhook routing and lifecycle behind a simple event-driven API.

Probot is safe for concurrent use: register handlers with On / OnAny / OnError and dispatch events with Receive.

func New

func New(o Options, defaults ...func(*Options)) (*Probot, error)

New creates a Probot instance. Either AppID + PrivateKey or GithubToken must be present (via Options or the supplied defaults). Initialization is synchronous — register handlers with On/OnAny/OnError after New.

func (*Probot) AppID

func (p *Probot) AppID() int64

AppID returns the numeric GitHub App ID, or 0 when the instance is unconfigured or uses a GithubToken.

func (*Probot) Auth

func (p *Probot) Auth(installationID ...int64) (*github.Client, error)

Auth returns an authenticated GitHub client. With no installationID it returns an app-level (JWT) client. With an installation ID it returns a client authenticated as that installation.

In webhook handlers prefer ctx.GitHub() / ctx.Octokit(), which are already authenticated for the triggering installation.

func (*Probot) Done

func (p *Probot) Done() <-chan struct{}

Done returns a channel closed once Probot has been initialized.

func (*Probot) Handler

func (p *Probot) Handler(next ...http.Handler) http.Handler

func (*Probot) Load

func (p *Probot) Load(fns ...ApplicationFunc) error

Load invokes one or more ApplicationFuncs with this Probot instance, mirroring probot's app.load(). Functions run synchronously, so handlers they register are available immediately.

func (*Probot) Log

func (p *Probot) Log() zerolog.Logger

Log returns the Probot logger.

func (*Probot) On

func (p *Probot) On(eventName string, fn HandlerFunc)

On subscribes to a webhook event. eventName may be a bare event name ("issues", matching any action) or an event with an action ("issues.opened").

func (*Probot) OnAny

func (p *Probot) OnAny(fn HandlerFunc)

OnAny subscribes to all webhook events.

func (*Probot) OnError

func (p *Probot) OnError(fn ErrorHandlerFunc)

OnError registers a handler for errors thrown inside webhook handlers.

func (*Probot) OnMany

func (p *Probot) OnMany(eventNames []string, fn HandlerFunc)

OnMany subscribes a single handler to several events.

func (*Probot) Options

func (p *Probot) Options() Options

Options returns a copy of the Probot's options.

func (*Probot) Ready

func (p *Probot) Ready() *Probot

Ready returns the Probot. Provided for API parity with probot's async ready(); in this Go port initialization is synchronous so Ready requires no waiting.

func (*Probot) Receive

func (p *Probot) Receive(event WebhookEvent) error

Receive dispatches a webhook event through the event pipeline. Errors raised by handlers are routed to the registered error handler (OnError) and also returned joined together. This mirrors probot's app.receive() and is useful for tests.

func (*Probot) RunAction

func (p *Probot) RunAction() error

RunAction reads GITHUB_EVENT_PATH and GITHUB_EVENT_NAME from the environment, loads the payload, and dispatches it to the registered handlers, then returns. This allows running your Probot app directly as a GitHub Action.

func (*Probot) Version

func (p *Probot) Version() string

Version returns the version of this port.

func (*Probot) WebhookHandler

func (p *Probot) WebhookHandler() http.HandlerFunc

func (*Probot) WebhookMiddleware

func (p *Probot) WebhookMiddleware() func(http.Handler) http.Handler

WebhookMiddleware returns a net/http middleware that handles webhook events. It is the Go equivalent of probot's getNodeMiddleware(): mount it in your own server. Requests to other paths are passed through.

func (*Probot) WebhookPath

func (p *Probot) WebhookPath() string

WebhookPath returns the URL path webhook events are expected on.

type PullRequestParams

type PullRequestParams = IssueParams

PullRequestParams identifies a pull request for go-github API calls.

type Repo

type Repo struct {
	Owner string
	Repo  string
}

Repo identifies a GitHub repository.

type Server

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

Server runs a Probot instance over HTTP: it mounts the webhook handler and a setup wizard (when no app is configured) at "/". This is the Go equivalent of probot's Server.

func NewServer

func NewServer(o ServerOptions) *Server

NewServer creates a Server.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the full HTTP handler for this server: the setup wizard at "/", its callback at "/setup/callback", and the webhook handler at the configured path.

func (*Server) Start

func (s *Server) Start() error

Start begins serving and blocks until the server stops or fails.

func (*Server) Stop

func (s *Server) Stop() error

Stop shuts the server down gracefully.

type ServerOptions

type ServerOptions struct {
	// Probot is the framework instance to serve. Required.
	Probot *Probot
	// Host to bind; defaults to the Probot option.
	Host string
	// Port to listen on; defaults to the Probot option (3000).
	Port int
	// WebhookPath to mount the webhook handler on; defaults to Probot option.
	WebhookPath string
	// EnvFile is where the setup wizard persists credentials. Defaults to
	// ".env" in the process working directory.
	EnvFile string
}

ServerOptions configure a Server.

type WebhookEvent

type WebhookEvent struct {
	// Name is the webhook event name, e.g. "issues".
	Name string
	// ID is a unique delivery ID (e.g. the X-GitHub-Delivery header).
	ID string
	// Payload is the parsed webhook JSON payload.
	Payload map[string]any
}

WebhookEvent is a single webhook delivery, used with Receive.

Directories

Path Synopsis
example
basic command
Command basic is a complete, minimal Probot app in Go.
Command basic is a complete, minimal Probot app in Go.

Jump to

Keyboard shortcuts

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