Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions go/MIDDLEWARE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Genkit Middleware (Go)

Middleware in Genkit allows you to wrap your Flows (or any Action) with custom logic. This is useful for cross-cutting concerns like logging, authentication, validation, or modifying inputs/outputs.

Middleware is defined as a function that takes a `StreamingFunc` and returns a `StreamingFunc`.

## Defining Middleware

A middleware function typically follows this pattern:

```go
package main

import (
"context"
"log"

"github.com/firebase/genkit/go/core"
)

func MyMiddleware[In, Out, Stream any](next core.StreamingFunc[In, Out, Stream]) core.StreamingFunc[In, Out, Stream] {
return func(ctx context.Context, input In, cb func(context.Context, Stream) error) (Out, error) {
// 1. Logic BEFORE the Flow runs
// e.g., validate input, start timer, check auth

// 2. Call the next handler in the chain
output, err := next(ctx, input, cb)

// 3. Logic AFTER the Flow runs
// e.g., log success/failure, modify output

return output, err
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

It's a standard convention to end files with a newline character. Please add one here.

Suggested change
}
}
2 changes: 2 additions & 0 deletions go/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@

This package is the Go version of Genkit, a framework for building
AI-powered apps. See: https://genkit.dev/go/docs/get-started-go

- [Middleware Guide](MIDDLEWARE.md): Learn how to add logging, authentication, and custom logic to your flows.