goflare

package module
v0.3.6 Latest Latest
Warning

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

Go to latest
Published: Jun 17, 2026 License: MIT Imports: 24 Imported by: 1

README

GoFlare

GoFlare is a self-contained Go tool (library + CLI) for deploying Go WASM projects to Cloudflare Workers and Pages. No Node.js, no Wrangler. Pure Go, direct Cloudflare API. Deploy runs in GitHub Actions — secrets never touch the developer's machine.

When to use

  • Cloudflare Pages Functions in Go (recommended) — static site + Go edge function deployed via CF Git Integration
  • Standalone Cloudflare Workers in Go (WASM)
  • Static Cloudflare Pages (Go WASM frontends)

The project mode is inferred from edge/main.go imports — no MODE variable in .env. See BUILD_PAGES_FUNCTIONS.md.

my-project/
├── .env                       # credentials — gitignored (NEVER tokens)
├── .env.example
├── routes/
│   └── routes.go              # build-agnostic — func Register(r router.Router)
├── modules/
│   └── contact/
│       ├── model.go           # build-agnostic — model + Validate()
│       └── handler.go         # build-agnostic — func Handle(ctx router.Context)
├── web/
│   ├── client.go              # //go:build wasm — frontend (browser)
│   ├── server.go              # //go:build !wasm — local dev server
│   └── public/                # static assets — committed; produced by tinywasm framework
│       ├── index.html
│       ├── client.wasm
│       ├── script.js
│       └── style.css
├── edge/
│   └── main.go                # //go:build wasm — entrypoint, imports goflare/pages
└── functions/                 # generated by goflare — COMMITTED
    ├── [[path]].mjs           # catch-all glue (exports onRequest)
    └── edge.wasm              # compiled edge/main.go

.env

PROJECT_NAME=my-app
# DOMAIN=example.com             # optional, custom domain for Pages

CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID are secrets — they live in GitHub Secrets, never in .env.

CLI

Install the CLI:

go install github.com/tinywasm/goflare/cmd/goflare@latest
  • goflare auth --check: Validate CLOUDFLARE_API_TOKEN from environment.
  • goflare build: Infer mode from edge/main.go imports and produce artifacts.
  • goflare deploy: Direct Upload v2. ⚠️ Designed for CI/CD environments. Now includes automatic Pages project provisioning and robust error reporting.

GitHub Setup

Deployment is designed to run in CI. Register secrets in: GitHub → Settings → Secrets and variables → Actions.

Name Type Description
CLOUDFLARE_API_TOKEN Secret API Token with Workers and Pages permissions
CLOUDFLARE_ACCOUNT_ID Secret Your Cloudflare Account ID
D1_DATABASE_ID Variable D1 database ID (optional)

For more details see CI_D1_SECRETS.md.

edge/main.go:

//go:build wasm

package main

import (
    "github.com/tinywasm/goflare/pages"   // ← this import sets MODE=pages-functions
    "github.com/your-project/routes"
)

func main() {
    r := pages.NewRouter()
    routes.Register(r)
    pages.Serve(r)
}

⚠️ Critical: NO heavy stdlib in wasm code

Files with //go:build wasm (everything under edge/, routes/, modules/, workers/, pages/pages.go, cloudflare/env_wasm.go) NEVER import fmt, strings, errors, encoding/*, net/http, log, io/ioutil. Use tinywasm/fmt, tinywasm/json, tinywasm/strings, tinywasm/fetch instead.

Stdlib inflates the wasm binary ~80% and exceeds Cloudflare Free's 1 MiB limit. TinyGo also does not fully support net/http in js/wasm.

Verification: grep -rE '^\s*"(fmt|strings|errors|encoding|net/http|log|io/ioutil)"' edge/ routes/ modules/ workers/ pages/pages.go cloudflare/env_wasm.go must return empty.

Library usage

cfg := &goflare.Config{
    ProjectName: "myapp",
    AccountID:   "acc-id",
}
g := goflare.New(cfg)
g.Build()
g.Deploy()

Config reference

Field .env key Default Notes
ProjectName PROJECT_NAME required
AccountID GitHub Secret CLOUDFLARE_ACCOUNT_ID required
WorkerName WORKER_NAME <ProjectName>-worker optional
Entry auto: edge Convention: edge/main.go
PublicDir auto: web/public Convention: web/public
Domain DOMAIN optional custom domain
CompilerMode COMPILER_MODE S S=small/prod, M=debug, L=Go std

Requirements

  • Go 1.25.2+
  • TinyGo — installed automatically by goflare build via tinywasm/tinygo

Documentation

Index

Constants

View Source
const (
	EnvKeyProjectName    = "PROJECT_NAME"
	EnvKeyAccountID      = "CLOUDFLARE_ACCOUNT_ID"
	EnvKeyWorkerName     = "WORKER_NAME"
	EnvKeyDomain         = "DOMAIN"
	EnvKeyCompilerMode   = "COMPILER_MODE"
	EnvKeyD1DatabaseID   = "D1_DATABASE_ID"
	EnvKeyD1DatabaseName = "D1_DATABASE_NAME"
)

Variables

View Source
var ErrNotFound = errors.New("not found")

Functions

func EnsureTinyGo added in v0.2.22

func EnsureTinyGo(out io.Writer) error

EnsureTinyGo installs TinyGo if absent and guarantees its bin dir is in PATH before any compilation attempt. Safe to call multiple times (idempotent).

func RunAuth added in v0.2.3

func RunAuth(envPath string, out io.Writer, check bool) error

RunAuth runs the auth command.

func RunBuild added in v0.1.0

func RunBuild(envPath string, out io.Writer) error

RunBuild runs the build command.

func RunDeploy added in v0.1.0

func RunDeploy(envPath string, out io.Writer) error

RunDeploy runs the deploy command.

func Usage added in v0.1.0

func Usage() string

Usage returns the usage string.

Types

type CfClient added in v0.3.0

type CfClient struct {
	Token      string
	BaseURL    string // default: cfAPIBase; overridden in tests
	HttpClient *http.Client
}

type Config

type Config struct {
	// Project identity
	ProjectName string // PROJECT_NAME
	AccountID   string // CLOUDFLARE_ACCOUNT_ID
	WorkerName  string // WORKER_NAME  (default: ProjectName + "-worker")

	// Routing
	Domain string // DOMAIN (optional — custom domain for Pages)

	// Build inputs (conventions, not configurable via .env)
	Entry     string // ENTRY      (path to main Go file, empty = Pages only)
	PublicDir string // PUBLIC_DIR (path to static assets, empty = Worker only)

	// Build output (not in .env — always .build/)
	OutputDir string // default: ".build/"

	// Pages Functions output (sibling to web/public/, committed to git)
	FunctionsDir string // default: "functions"

	// Compiler
	CompilerMode string // "S" | "M" | "L"  default: "S"

	D1DatabaseID   string // D1_DATABASE_ID
	D1DatabaseName string // D1_DATABASE_NAME — optional, default: ProjectName
}

func LoadConfigFromEnv added in v0.1.0

func LoadConfigFromEnv(path string) (*Config, error)

LoadConfigFromEnv reads a .env file and populates Config. Falls back to OS environment variables if .env path is empty or does not exist. Applies defaults after loading.

func (*Config) ValidateBuild added in v0.2.17

func (c *Config) ValidateBuild() error

ValidateBuild checks only what goflare build requires. ProjectName and AccountID are deploy-only — never referenced by build.go.

func (*Config) ValidateDeploy added in v0.2.17

func (c *Config) ValidateDeploy() error

ValidateDeploy checks everything required for a Cloudflare API deploy.

type DeployResult added in v0.1.0

type DeployResult struct {
	Target string
	URL    string
	Err    error
}

DeployResult represents the result of a deployment to a target.

type Goflare

type Goflare struct {
	Config *Config // exported so CLI can read it after LoadConfigFromEnv

	BaseURL string

	RetryBackoff time.Duration // base duration for retries (defaults to 1s)
	// contains filtered or unexported fields
}

func New

func New(cfg *Config) *Goflare

New creates a new Goflare instance with the provided configuration

func (*Goflare) Auth added in v0.0.97

func (g *Goflare) Auth() error

Auth implements token validation.

func (*Goflare) Build added in v0.1.0

func (g *Goflare) Build() error

Build orchestrates the build pipeline as a method.

Mode is inferred from edge/main.go imports (D11):

  • pages-functions: edge/main.go imports github.com/tinywasm/goflare/pages → output functions/[path].mjs + functions/edge.wasm
  • workers: edge/main.go imports github.com/tinywasm/goflare/workers → output .build/edge.js + .build/edge.wasm (legacy)
  • pages (static): no edge/main.go but PublicDir exists → only static + optional frontend wasm

func (*Goflare) Change

func (h *Goflare) Change(newValue string, progress func(msgs ...any))

func (*Goflare) Deploy added in v0.1.0

func (g *Goflare) Deploy() error

func (*Goflare) DeployPages added in v0.0.97

func (g *Goflare) DeployPages() error

func (*Goflare) DeployWorker added in v0.0.99

func (g *Goflare) DeployWorker() error

func (*Goflare) GeneratePagesFiles

func (g *Goflare) GeneratePagesFiles() error

func (*Goflare) GenerateWorkerFiles

func (g *Goflare) GenerateWorkerFiles() error

func (*Goflare) Label

func (h *Goflare) Label() string

func (*Goflare) Logger added in v0.0.40

func (g *Goflare) Logger(messages ...any)

func (*Goflare) MainInputFileRelativePath

func (h *Goflare) MainInputFileRelativePath() string

MainInputFileRelativePath returns the relative path to the main input file This is used by devwatch to determine file ownership for Go files

func (*Goflare) Name

func (h *Goflare) Name() string

func (*Goflare) NewFileEvent

func (h *Goflare) NewFileEvent(fileName, extension, filePath, event string) error

NewFileEvent handles file change events for goflare This method is called by devwatch when a relevant file changes

func (*Goflare) SetCompilerMode

func (g *Goflare) SetCompilerMode(newValue string)

SetCompilerMode changes the compiler mode mode: "L" (Large fast/Go), "M" (Medium TinyGo debug), "S" (Small TinyGo production)

func (*Goflare) SetLog added in v0.0.40

func (g *Goflare) SetLog(f func(message ...any))

func (*Goflare) Shortcuts

func (h *Goflare) Shortcuts() []map[string]string

func (*Goflare) StagingDir added in v0.2.13

func (g *Goflare) StagingDir() string

StagingDir returns the temporary directory used for intermediate build artifacts. Exposed for testing — verifies that staging is outside the project tree.

func (*Goflare) SupportedExtensions

func (h *Goflare) SupportedExtensions() []string

SupportedExtensions returns the file extensions that goflare monitors For edge workers, we primarily watch .go files

func (*Goflare) UnobservedFiles

func (h *Goflare) UnobservedFiles() []string

UnobservedFiles returns files that should be ignored by the file watcher These are output files generated by goflare that shouldn't trigger recompilation

func (*Goflare) ValidateDeployScopes added in v0.3.0

func (g *Goflare) ValidateDeployScopes(client *CfClient) error

DeployPages uploads the Pages build output (from config.OutputDir) to Cloudflare Pages. validateDeployScopes confirms that the token has the necessary permissions to manage Pages projects and deployments.

func (*Goflare) Value

func (h *Goflare) Value() string

func (*Goflare) WriteSummary added in v0.1.0

func (g *Goflare) WriteSummary(out io.Writer, results []DeployResult)

WriteSummary formats and writes the deploy summary to out.

type MemoryStore added in v0.1.0

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

MemoryStore is an in-memory Store exported for use by library consumers in tests. Safe for concurrent use.

func NewMemoryStore added in v0.1.0

func NewMemoryStore() *MemoryStore

func (*MemoryStore) Get added in v0.1.0

func (s *MemoryStore) Get(key string) (string, error)

func (*MemoryStore) Set added in v0.1.0

func (s *MemoryStore) Set(key, value string) error

type Mode added in v0.2.6

type Mode string

Mode represents the inferred project build mode.

const (
	ModeUnknown        Mode = ""
	ModeWorkers        Mode = "workers"
	ModePagesFunctions Mode = "pages-functions"
	ModePagesStatic    Mode = "pages"
)

type Store added in v0.0.99

type Store interface {
	Get(key string) (string, error)
	Set(key, value string) error
}

Store abstracts access for testability.

Directories

Path Synopsis
cmd
goflare command

Jump to

Keyboard shortcuts

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