File Storage
Export the saved photo list as a JSON file through a storage disk. Keep photo records and ownership in SQLite. Use disks for file contents, including uploads, private documents, public assets, and generated exports.
When to Use Storage
Start with local storage when one host owns the files. Use memory storage in focused tests. Choose shared object storage or a remote filesystem when API and worker processes on different hosts need the same files.
A disk is the named resource your code selects. Its driver determines where the bytes live. Relational metadata, authorization state, and transactional updates still belong in the database.
Access Storage from Application Code
Start with Save and List Photos. Stop forj dev while you add storage to the existing render.components list in .goforj.yml. Preserve the other components, then run:
forj renderIn .env, configure the default disk:
STORAGE_SUPPORTED_DRIVERS=local
STORAGE_DRIVER=local
STORAGE_ROOT=storage/app/privateThe manager in internal/storages exposes Default() and named disks such as Public(). The root app exposes the manager through app.Storage(). Inject the manager into application code and select the disk in its constructor.
Export the Photo List
Generate a command and its registration:
forj make:command photos:export --no-openReplace internal/photos/export_cmd.go with the following file. Replace your/module with the module path in go.mod.
package photos
import (
"context"
"encoding/json"
"fmt"
"github.com/goforj/storage"
"your/module/internal/storages"
)
// ExportCmd writes a snapshot of the saved photo metadata.
type ExportCmd struct {
service *Service
disk storage.Storage
}
// Signature exposes the command through the app CLI.
func (*ExportCmd) Signature() string {
return `name:"photos:export" help:"Export saved photo metadata"`
}
// NewExportCmd selects the configured default disk for private exports.
func NewExportCmd(service *Service, manager *storages.Manager) *ExportCmd {
return &ExportCmd{service: service, disk: manager.Default()}
}
// Run replaces the previous export only after the photo query succeeds.
func (c *ExportCmd) Run(ctx context.Context) error {
photos, err := c.service.ListNewest(ctx)
if err != nil {
return err
}
contents, err := json.Marshal(photos)
if err != nil {
return err
}
const key = "reports/photos/latest.json"
if err := c.disk.WithContext(ctx).Put(key, contents); err != nil {
return err
}
fmt.Println(key)
return nil
}The command generator registers NewExportCmd in the app's Wire providers. Build and run the command from the Project root:
forj build
forj photos:export
# reports/photos/latest.json
cat storage/app/private/reports/photos/latest.json
# [{"id":1,"storage_key":"sunrise.jpg"}]The JSON contains your saved records, so IDs and keys can differ. The storage key is relative to the disk root. Put replaces an existing object at that key. If you also applied Cache, the exported list can be up to 30 seconds old.
The disk's private root does not create an HTTP download route. Add authentication and ownership checks when you expose an export or an uploaded file. URL generation depends on the driver's capabilities and configuration. Handle unsupported operations explicitly.
Choosing Storage Drivers
| Need | Driver choice |
|---|---|
| Local development | local |
| Focused service tests | memory |
| One host owns persistent files | local with a persistent volume and backups |
| Several hosts read the same files | Object storage or a shared remote filesystem |
| Public asset delivery | A disk with configured public URLs or CDN delivery |
| Temporary shared blobs | Redis with explicit size and durability limits |
STORAGE_SUPPORTED_DRIVERS selects the drivers compiled into the binary. Runtime disk settings select an enabled driver. For example, keep the default disk local and add an uploads disk:
STORAGE_SUPPORTED_DRIVERS=local,s3
STORAGE_DRIVER=local
STORAGE_ROOT=storage/app/private
STORAGE_PUBLIC_DRIVER=local
STORAGE_PUBLIC_ROOT=storage/app/public
STORAGE_UPLOADS_DRIVER=s3
STORAGE_UPLOADS_BUCKET=my-app-uploads
STORAGE_UPLOADS_REGION=us-east-1Complete the driver credentials and endpoint settings, then run forj build. The uploads disk becomes available as app.Storage().Uploads() or manager.Uploads() in an injected service. During forj dev, an app listed in dev.apps rebuilds after environment changes. See Generation Commands for focused generation workflows.
Path Discipline
Use stable keys scoped to an owner or record, such as users/{userID}/avatars/current.png or reports/{reportID}/exports/latest.csv. Keep bucket names and local roots in configuration so a driver change does not require changing stored keys.
Do not trust raw filenames or paths from a request. Validate and normalize them at the input boundary. Generate the storage key in application code, and check ownership before reading or writing it. A fixed export key deliberately overwrites the previous snapshot. Use a unique export ID when callers need independent snapshots or concurrent writers must not replace each other's output.
Consistency with Database
Database transactions do not include storage writes. The export command reads committed rows and writes a derived file, so it can regenerate a failed export without creating another database record.
Uploads need an explicit policy for partial failure. If you write the blob first and the database insert fails, delete the orphaned blob or record cleanup work for retry. If you create the row first and the blob write fails, mark the upload incomplete or remove the row. Do not present an incomplete upload as ready.
Choose stable operation IDs so retries do not create duplicate rows or objects. Decide whether missing blobs can be regenerated. Keep cleanup failures visible and retry them. A storage error does not guarantee that no bytes were written, so test the selected driver's failure behavior before relying on replacement semantics.
Testing and Operations
Test the export with a memory disk. Assert the exact key and JSON bytes, and verify that a failed query leaves an existing export untouched. Simulate a storage write failure and confirm that the command returns the error. For workflows that write rows and blobs, cover both partial failures: a committed row with a failed blob write, and a written blob with a failed database insert.
Before releasing a remote driver, send a non-production object through the same app workflow used by customers:
- Write the object through its owning API, command, or worker.
- Read it through a different deployed process when the disk must be shared.
- Check its contents and authorization behavior.
- Delete it through the normal cleanup path.
- Confirm the object is gone and its audit or business metadata remains correct.
Readiness checks disk construction and access. It does not establish bucket policy, URL behavior, cross-host visibility, or cleanup permissions. With local storage, also check that deployment preserves the configured root across container replacement.
Local and Production Drivers
Use the storage library reference for the supported driver and capability matrices, including S3, GCS, FTP, SFTP, Dropbox, rclone, and Redis. Select the driver for the required sharing, durability, and access behavior. A local path on one host does not give a worker on another host access to those files.
Next Steps
- Named Resources explains named disks.
- Driver Selection compares backend requirements.
- Environment Reference lists disk settings.
- Storage documents standalone construction and the full package API.