Skip to content

Instantly share code, notes, and snippets.

@vikram-dagger
Created August 1, 2025 19:19
Show Gist options
  • Save vikram-dagger/84beb32371a270247fa7a4c54a5539b1 to your computer and use it in GitHub Desktop.
Save vikram-dagger/84beb32371a270247fa7a4c54a5539b1 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"math/rand"
"time"
"dagger/book/internal/dagger"
)
func New(
// +defaultPath="."
source *dagger.Directory,
) *Book {
return &Book{
Source: source,
}
}
type Book struct {
// The source directory of the app
Source *dagger.Directory
}
// Env sets up a Python environment with dependencies installed.
func (b *Book) Env(ctx context.Context) (*dagger.Container, error) {
return dag.Container().
From("python:3.11").
WithDirectory("/app", b.Source).
WithWorkdir("/app").
WithMountedCache("/root/.cache/pip", dag.CacheVolume("python-pip")).
WithExec([]string{"pip", "install", "-r", "requirements.txt"}), nil
}
// Test spins up a Postgres service, sets up the environment, and runs pytest.
func (b *Book) Test(ctx context.Context) (string, error) {
postgres := dag.Container().
From("postgres:alpine").
WithEnvVariable("POSTGRES_DB", "app_test").
WithEnvVariable("POSTGRES_PASSWORD", "secret").
WithExposedPort(5432).
AsService()
env, err := b.Env(ctx)
if err != nil {
return "", err
}
testContainer := env.
WithServiceBinding("db", postgres).
WithEnvVariable("DATABASE_URL", "postgresql://postgres:secret@db/app_test").
WithExec([]string{"pytest"})
return testContainer.Stdout(ctx)
}
// Publish runs tests and publishes the FastAPI app container.
func (b *Book) Publish(ctx context.Context) (string, error) {
// Run tests first
if _, err := b.Test(ctx); err != nil {
return "", err
}
env, err := b.Env(ctx)
if err != nil {
return "", err
}
r := rand.New(rand.NewSource(time.Now().UnixNano()))
tag := fmt.Sprintf("ttl.sh/my-fastapi-app-%d", r.Intn(1e8))
return env.
WithExposedPort(8000).
WithEntrypoint([]string{"fastapi", "run", "main.py"}).
Publish(ctx, tag)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment