slacktonic

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2025 License: MIT Imports: 8 Imported by: 0

README

slacktonic

Go Reference Go Report Card

A Go middleware for handling Slack slash commands in Gin applications.

Features

  • Verifies Slack request signatures using your signing secret
  • Parses slash commands from requests
  • Makes slash commands available in your Gin handlers

Installation

go get github.com/vpriem/slacktonic

Usage

package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/vpriem/slacktonic"
)

func main() {
	r := gin.Default()

	// Add the middleware to verify Slack requests
	r.Use(slacktonic.Middleware("your-slack-signing-secret"))

	// Handle slash commands
	r.POST("/slack", func(c *gin.Context) {
		// Get the slash command from the context
		cmd, ok := slacktonic.GetSlashCommand(c)
		if !ok {
			c.JSON(http.StatusBadRequest, gin.H{"error": "No slash command found"})
			return
		}

		// Handle the command
		switch cmd.Command {
		case "/hello":
			c.JSON(http.StatusOK, gin.H{"text": "Hello, " + cmd.UserName + "!"})
		default:
			c.JSON(http.StatusOK, gin.H{"text": "Unknown command: " + cmd.Command})
		}
	})

	r.Run(":8080")
}

Configuration Options

The middleware can be configured using option functions passed to the Middleware function:

Custom Logging

By default, the middleware uses a no-op logger that discards all log messages. You can provide your own logger that implements the Logger interface using the WithLogger option function:

logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
r.Use(slacktonic.Middleware("your-slack-signing-secret", slacktonic.WithLogger(logger)))

The logger interface is compatible with Go's standard log/slog package.

Custom Verifier

By default, the middleware uses a SlackVerifier that verifies Slack request signatures using the provided signing secret. You can provide your own verifier that implements the Verifier interface using the WithVerifier option function:

// For testing purposes
mockVerifier := &MockVerifier{} // implements the Verifier interface
r.Use(slacktonic.Middleware("", slacktonic.WithVerifier(mockVerifier)))

This option is primarily intended for testing your integration with Slack. It allows you to mock the verification process during tests, making it possible to test your handlers without needing real Slack credentials or making actual API calls.

Command Validation

You can specify an expected command to validate incoming slash commands. If the received command doesn't match the expected one, the middleware will return a 400 Bad Request response:

// Only accept the /hello command
r.Use(slacktonic.Middleware("your-slack-signing-secret", slacktonic.WithCommand("/hello")))

This is useful when you want to ensure that only specific commands are processed by your handler.

License

See LICENSE file.

Documentation

Overview

Package slacktonic provides middleware for handling Slack slash commands in Gin applications.

Package slacktonic provides middleware for handling Slack slash commands in Gin applications.

Package slacktonic provides middleware for handling Slack slash commands in Gin applications.

It verifies the authenticity of incoming Slack requests using the signing secret and parses slash commands, making them available in the Gin context.

Example usage:

r := gin.New()
r.Use(slacktonic.Middleware("your-slack-signing-secret"))
r.POST("/slack", func(c *gin.Context) {
	cmd, ok := slacktonic.GetSlashCommand(c)
	if ok {
		// Handle the slash command
	}
})

Index

Constants

This section is empty.

Variables

View Source
var ErrUnauthorized = fmt.Errorf("unauthorized")

Functions

func GetSlashCommand

func GetSlashCommand(c *gin.Context) (slack.SlashCommand, bool)

GetSlashCommand retrieves the Slack slash command from the Gin context.

This function should be called after the Middleware has processed the request. The Middleware stores the slash command in the context if it was successfully parsed from the request.

Parameters:

  • c: The Gin context from which to retrieve the slash command

Returns:

  • slack.SlashCommand: The slash command if it exists in the context
  • bool: true if the slash command was found, false otherwise

func Middleware

func Middleware(secret string, optFns ...Option) gin.HandlerFunc

Middleware returns a Gin middleware function that verifies Slack requests and parses slash commands.

The middleware: 1. Verifies the request using the provided Verifier (or creates a SlackVerifier with the provided secret) 2. Parses the slash command from the request 3. Validates the command against the expected command (if specified using WithCommand) 4. Stores the slash command in the Gin context for later retrieval

Parameters:

  • secret: The Slack signing secret used to verify request authenticity
  • optFns: Optional configuration functions for the middleware (WithCommand, WithLogger, WithVerifier)

Returns a Gin HandlerFunc that can be used with the Gin router.

Types

type Logger

type Logger interface {
	// InfoContext logs an info message with the given context and key-value pairs.
	InfoContext(ctx context.Context, msg string, args ...any)

	// WarnContext logs a warning message with the given context and key-value pairs.
	WarnContext(ctx context.Context, msg string, args ...any)

	// ErrorContext logs an error message with the given context and key-value pairs.
	ErrorContext(ctx context.Context, msg string, args ...any)
}

Logger is an interface for logging errors that occur during request processing. It is designed to be compatible with the standard library's log/slog package.

type Option

type Option func(*Options)

func WithCommand

func WithCommand(command string) Option

WithCommand specifies the expected slash command. If provided, the middleware will check if the received command matches this value. If the command doesn't match, a 400 Bad Request response will be returned.

func WithLogger

func WithLogger(l Logger) Option

WithLogger sets a logger for the middleware. Logger is used to log errors that occur during request processing. If not provided, a no-op logger will be used.

func WithVerifier

func WithVerifier(v Verifier) Option

WithVerifier sets a custom verifier for the middleware. Verifier is used to verify Slack requests and parse slash commands. If not provided, a SlackVerifier will be created using the provided secret.

type Options

type Options struct {
	Logger   Logger
	Command  string
	Verifier Verifier
}

Options configures the behavior of the middleware. It is configured through option functions passed to the Middleware function.

type SlackVerifier

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

SlackVerifier is the default implementation of the Verifier interface. It verifies Slack request signatures using the provided signing secret.

func NewVerifier

func NewVerifier(secret string) *SlackVerifier

NewVerifier creates a new SlackVerifier with the provided signing secret.

func (*SlackVerifier) Verify

func (s *SlackVerifier) Verify(req *http.Request) (slack.SlashCommand, error)

Verify verifies the authenticity of a Slack request using the signing secret and parses the slash command from the request. It returns the parsed slash command and nil if verification succeeds, or nil and an error if verification fails.

type Verifier

type Verifier interface {
	// Verify verifies the authenticity of a Slack request and parses the slash command.
	// It returns the parsed slash command and nil if verification succeeds,
	// or nil and an error if verification fails.
	Verify(*http.Request) (slack.SlashCommand, error)
}

Verifier is an interface for verifying Slack requests and parsing slash commands. It allows for custom verification logic or mocking during tests.

Jump to

Keyboard shortcuts

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