fireimg

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2026 License: MIT Imports: 15 Imported by: 0

README

fireimg (Go)

Server-side Go client for API-key uploads, optional moderation, listing, and CDN URLs. It handles the two-step presigned upload (request URLs, then PUT to S3) the same way the FireImg CLI and Ruby gem do.

client, err := fireimg.New(fireimg.Config{
    APIKey:  os.Getenv("FIREIMG_API_KEY"),
    Project: os.Getenv("FIREIMG_PROJECT"),
})

result, err := client.Upload(ctx, fireimg.Upload{
    Filename:    "hero.jpg",
    ContentType: "image/jpeg",
    Path:        "./hero.jpg",
})
// result.CDNURL => https://img.fireimg.com/your-project/images/hero.jpg

Create an API key under API Keys in the FireImg app. The full secret is shown only once.

Install

go get github.com/FirelitStudio/fireimg-go
import "github.com/FirelitStudio/fireimg-go"

Configure

client, err := fireimg.New(fireimg.Config{
    APIKey:  os.Getenv("FIREIMG_API_KEY"),
    Project: os.Getenv("FIREIMG_PROJECT"),
    APIBase: os.Getenv("FIREIMG_API_BASE"), // optional; default https://api.fireimg.com
    CDNBase: os.Getenv("FIREIMG_CDN_BASE"), // optional; default https://img.fireimg.com
})

FIREIMG_API_KEY and FIREIMG_PROJECT (and the base URL variables) are also read automatically when those fields are empty. Prefer environment variables so the key does not appear in source or process lists.

Staging:

client, err := fireimg.New(fireimg.Config{
    APIBase: "https://api.fireimg.dev",
    CDNBase: "https://img.fireimg.dev",
})

URL helpers work without an API key. Upload, delete, moderate, and list require both APIKey and Project.

Upload

Upload requests a presigned URL, then PUTs the bytes:

result, err := client.Upload(ctx, fireimg.Upload{
    Filename:    "feed_items/43/uuid.jpg",
    ContentType: "image/jpeg",
    Path:        "/tmp/photo.jpg", // or Body / Bytes
    Sizes: []fireimg.Size{
        {Width: 800, Quality: "medium", Fmt: "webp"},
        {Width: 160, Height: 160, Fit: "cover", Pos: "center", Fmt: "webp"},
    },
})

result.ImageKey // "feed_items/43/uuid.jpg"
result.CDNURL   // https://img.fireimg.com/{project}/images/feed_items/43/uuid.jpg

Filename may include folders. Provide the bytes with Path, Body, or Bytes.

Optional Sizes (up to 20) are generated asynchronously after the PUT and replace the project's default image params for that upload. Omit Sizes (nil) to keep project defaults. Pass Sizes: []fireimg.Size{} to pre-generate only FireImg's 80px dashboard thumbnail.

UploadMany batches the same way as the CLI (up to 20 files per presign request). Shared sizes come from the first file that sets them. After one presign response, S3 PUTs run in parallel, up to MaxConcurrentPuts (4). The first PUT error cancels the rest.

result, err := client.Upload(ctx, fireimg.Upload{
    Filename:    "posts/kyoto/hero.jpg",
    ContentType: "image/jpeg",
    Body:        bytes.NewReader(data),
    Sizes:       fireimg.SizesForWidths([]int{320, 480, 640, 768, 960, 1280}),
})

CDN transforms are on-demand after the PUT. The client does not wait for optimization jobs.

If the client PUTs directly (mobile or browser), use Presign / PresignMany and PUT to result.UploadURL with the same Content-Type. See the API reference.

Moderate, delete, and list

labels, err := client.Moderate(ctx, "feed_items/43/uuid.jpg")
err = client.Delete(ctx, "feed_items/43/uuid.jpg")

projects, err := client.ListProjects(ctx)
page, err := client.ListImages(ctx, fireimg.ListImagesParams{Limit: 100, Folder: "feed_items"})

Moderation returns FireImg labels; your app applies policy.

URLs

These helpers work with only Project set (no API key):

client.PublicURL("feed_items/43/uuid.jpg")
// https://img.fireimg.com/{project}/images/feed_items/43/uuid.jpg

client.URL("feed_items/43/uuid.jpg", fireimg.Options{Width: 800, Quality: "medium", Format: "webp"})
// …/images/feed_items/43/uuid.jpg?width=800&quality=medium&format=webp

client.RawURL("feed_items/43/uuid.jpg")
// https://img.fireimg.com/raw-images/{project}/feed_items/43/uuid.jpg

srcset := client.SrcSet("hero.jpg", fireimg.SrcSetOptions{
    Widths:  []int{320, 640, 960},
    Options: fireimg.Options{Quality: "high", Format: "auto"},
})
// or snap a range: MinWidth, MaxWidth, SnapStep

sizes := fireimg.SizesAttr(960) // (max-width: 960px) 100vw, 960px

Supported options match the Image URL reference: Width, Height, Quality, Format / Fmt, Fit, Pos / Position, Fill, and Version. Only set fields are emitted; quality is not defaulted.

To change the width on an existing FireImg URL:

src := fireimg.RewriteURL(existing, fireimg.Options{Width: 960})
srcset := fireimg.SrcSetFromURL(existing, fireimg.SrcSetOptions{Widths: []int{320, 640, 960}})

GuessContentType and SanitizeFilename are available for upload prep.

CLI

For uploads from a terminal, CI job, or coding agent, use the FireImg CLI instead.

License

MIT

Documentation

Index

Constants

View Source
const (
	// DefaultAPIBase is the production FireImg API.
	DefaultAPIBase = "https://api.fireimg.com"
	// DefaultCDNBase is the production FireImg CDN.
	DefaultCDNBase = "https://img.fireimg.com"
	// MaxFilesPerRequest is the API limit for one presign call.
	MaxFilesPerRequest = 20
	// MaxSizesPerRequest is the API limit for pre-generated variants.
	MaxSizesPerRequest = 20
	// MaxConcurrentPuts is how many S3 PUTs UploadMany runs at once.
	MaxConcurrentPuts = 4
)
View Source
const Version = "0.1.1"

Version is the library version used in the User-Agent header.

Variables

This section is empty.

Functions

func BuildRawURL

func BuildRawURL(cdnBase, project, imageKey string) string

BuildRawURL constructs a raw-bytes CDN URL.

func BuildSrcSet

func BuildSrcSet(cdnBase, project, imageKey string, opts SrcSetOptions) string

BuildSrcSet constructs a srcset string for an image key.

func BuildURL

func BuildURL(cdnBase, project, imageKey string, opts Options) string

BuildURL constructs a CDN URL. cdnBase defaults to DefaultCDNBase.

func GuessContentType

func GuessContentType(filename, headerType string) string

GuessContentType returns headerType when it is a usable MIME type, otherwise an image type inferred from the filename extension.

func IsURL

func IsURL(src string) bool

IsURL reports whether src is a FireImg CDN URL.

func RewriteURL

func RewriteURL(src string, opts Options) string

RewriteURL applies opts to an existing URL. Existing query params are kept unless overwritten. Width and height are updated only when greater than zero.

func SanitizeFilename

func SanitizeFilename(name string) string

SanitizeFilename cleans an image key. Folders are preserved; each segment keeps letters, digits, dot, dash, and underscore. ".." is rejected.

func SizesAttr

func SizesAttr(maxWidth int) string

SizesAttr is an HTML sizes attribute for a max display width.

func SrcSetFromURL

func SrcSetFromURL(src string, opts SrcSetOptions) string

SrcSetFromURL builds a srcset by rewriting widths on an existing FireImg URL.

Types

type Client

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

Client talks to the FireImg API and builds CDN URLs.

func New

func New(cfg Config) (*Client, error)

New returns a client. Empty config fields fall back to FIREIMG_* environment variables. URL helpers work without an API key; upload and management calls require both APIKey and Project.

func (*Client) Configured

func (c *Client) Configured() bool

Configured reports whether API-key operations can run.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, imageKey string) error

Delete soft-deletes an image by key.

func (*Client) ListImages

func (c *Client) ListImages(ctx context.Context, params ListImagesParams) (*ListImagesResponse, error)

ListImages returns one page of images for the configured project.

func (*Client) ListProjects

func (c *Client) ListProjects(ctx context.Context) ([]Project, error)

ListProjects returns every project the API key's team can access.

func (*Client) Moderate

func (c *Client) Moderate(ctx context.Context, imageKey string) (*ModerationResult, error)

Moderate runs a Rekognition content scan. JPEG and PNG only. The result is labels for the app to apply policy; FireImg does not reject the image.

func (*Client) Presign

func (c *Client) Presign(ctx context.Context, filename, contentType string, sizes []Size) (*PresignResult, error)

Presign requests one presigned S3 PUT URL.

func (*Client) PresignMany

func (c *Client) PresignMany(ctx context.Context, files []FileSpec, sizes []Size) ([]PresignResult, error)

PresignMany requests presigned S3 PUT URLs for up to MaxFilesPerRequest files. A nil sizes slice omits the field; a non-nil empty slice sends [].

func (*Client) PublicURL

func (c *Client) PublicURL(imageKey string) string

PublicURL is the CDN URL with no transform query parameters.

func (*Client) Put

func (c *Client) Put(ctx context.Context, uploadURL, contentType string, body io.Reader) error

Put uploads raw bytes to a presigned S3 URL. It does not send the API key.

func (*Client) RawURL

func (c *Client) RawURL(imageKey string) string

RawURL is the unmodified bytes at /raw-images/{project}/{imageKey}.

func (*Client) SrcSet

func (c *Client) SrcSet(imageKey string, opts SrcSetOptions) string

SrcSet builds a comma-separated srcset from Widths or a min/max/step range.

func (*Client) URL

func (c *Client) URL(imageKey string, opts Options) string

URL is the CDN URL with the given transform options. Only set fields are emitted. The query key for format is "format"; Options.Fmt is accepted as an alias.

func (*Client) Upload

func (c *Client) Upload(ctx context.Context, file Upload) (*UploadResult, error)

Upload requests a presigned URL and PUTs the bytes.

func (*Client) UploadMany

func (c *Client) UploadMany(ctx context.Context, files []Upload) ([]UploadResult, error)

UploadMany presigns and PUTs up to MaxFilesPerRequest files. Shared Sizes come from the first file that sets them (including an explicit empty slice).

type Config

type Config struct {
	APIKey     string
	Project    string
	APIBase    string
	CDNBase    string
	HTTPClient *http.Client
}

Config holds client settings. Empty APIKey, Project, APIBase, and CDNBase fall back to FIREIMG_API_KEY, FIREIMG_PROJECT, FIREIMG_API_BASE, and FIREIMG_CDN_BASE. Staging uses https://api.fireimg.dev and https://img.fireimg.dev.

type Error

type Error struct {
	Op      string
	Status  int
	Message string
}

Error is a FireImg client or API failure.

func (*Error) Error

func (e *Error) Error() string

type FileSpec

type FileSpec struct {
	Filename    string `json:"filename"`
	ContentType string `json:"contentType"`
}

FileSpec is one file in a presign request.

type Image

type Image struct {
	ImageKey                 string `json:"imageKey"`
	S3RawKey                 string `json:"s3RawKey"`
	UploadedAt               string `json:"uploadedAt"`
	OriginalSizeBytes        int64  `json:"originalSizeBytes"`
	ContentType              string `json:"contentType"`
	VariationsGeneratedCount int    `json:"variationsGeneratedCount,omitempty"`
	CacheVersion             int    `json:"cacheVersion,omitempty"`
}

Image is one entry from GET /v1/api/projects/{slug}/images.

type ListImagesParams

type ListImagesParams struct {
	Limit     int
	NextToken string
	Folder    string
}

ListImagesParams are query options for GET /v1/api/projects/{slug}/images.

type ListImagesResponse

type ListImagesResponse struct {
	Images    []Image `json:"images"`
	Folder    string  `json:"folder"`
	NextToken string  `json:"nextToken,omitempty"`
}

ListImagesResponse is one page of images.

type ModerationLabel

type ModerationLabel struct {
	Name       string  `json:"name"`
	Parent     string  `json:"parent"`
	Confidence float64 `json:"confidence"`
}

ModerationLabel is one Rekognition label from a content scan.

type ModerationResult

type ModerationResult struct {
	Moderation string            `json:"moderation"`
	Labels     []ModerationLabel `json:"labels,omitempty"`
	Reason     string            `json:"reason,omitempty"`
}

ModerationResult is the body of POST .../images/moderation/{imageKey}.

type Options

type Options struct {
	Width    int
	Height   int
	Quality  string
	Format   string
	Fmt      string
	Fit      string
	Pos      string
	Position string
	Fill     string
	Version  int
}

Options are CDN transform query parameters. Only set fields are emitted; quality and format are not defaulted.

type PresignResult

type PresignResult struct {
	Filename      string
	UploadURL     string
	S3Key         string
	ExpiresInSecs int
}

PresignResult is one entry from POST /v1/api/presigned-upload-urls.

type Project

type Project struct {
	ProjectName string `json:"projectName"`
	Slug        string `json:"slug"`
	TeamID      string `json:"teamId,omitempty"`
	CreatedAt   string `json:"createdAt"`
}

Project is one entry from GET /v1/api/projects.

type Size

type Size struct {
	Width   int    `json:"width,omitempty"`
	Height  int    `json:"height,omitempty"`
	Quality string `json:"quality,omitempty"`
	Fmt     string `json:"fmt,omitempty"`
	Fit     string `json:"fit,omitempty"`
	Pos     string `json:"pos,omitempty"`
	Fill    string `json:"fill,omitempty"`
}

Size is one variant to pre-generate after upload. These replace the project's default image params for that upload. An empty slice still overrides defaults and pre-generates only FireImg's 80px dashboard thumbnail.

func SizesForWidths

func SizesForWidths(widths []int) []Size

SizesForWidths builds width-only pre-generation sizes.

type SrcSetOptions

type SrcSetOptions struct {
	Widths   []int
	MinWidth int
	MaxWidth int
	SnapStep int
	Options  Options
}

SrcSetOptions build a responsive srcset. Use Widths for an explicit ladder, or MinWidth/MaxWidth/SnapStep (defaults 100/2000/100) like @fireimg/js.

type Upload

type Upload struct {
	Filename    string
	ContentType string
	Body        io.Reader
	Bytes       []byte
	Path        string
	Sizes       []Size
}

Upload is one file to presign and PUT.

Provide bytes with Body, Bytes, or Path. Sizes is optional: nil keeps the project defaults; a non-nil empty slice sends [] and pre-generates only the dashboard thumbnail.

type UploadResult

type UploadResult struct {
	Filename string
	ImageKey string
	CDNURL   string
	S3Key    string
}

UploadResult is returned after a successful presign + PUT.

Jump to

Keyboard shortcuts

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