Storage
Nika provides an S3-compatible storage helper through common/storage. Configure it once during application bootstrap, then use the package-level functions anywhere in your project.
Installation
The S3 client is included by the framework dependency.
Setup
Configure Once
package main
import (
"github.com/nika-framework/nika"
"github.com/nika-framework/nika/common/config"
"github.com/nika-framework/nika/common/storage"
)
func main() {
app := nika.NewApp()
cfg := config.Setup(app, "")
err := storage.NewStorage(storage.Config{
Endpoint: cfg.GetString("S3_ENDPOINT", ""),
Region: cfg.GetString("S3_REGION", "us-east-1"),
Bucket: cfg.GetString("S3_BUCKET", ""),
AccessKey: cfg.GetString("S3_ACCESS_KEY", ""),
SecretKey: cfg.GetString("S3_SECRET_KEY", ""),
ForcePathStyle: cfg.GetBool("S3_FORCE_PATH_STYLE", true),
PublicURL: cfg.GetString("S3_PUBLIC_URL", ""),
})
if err != nil {
panic(err)
}
app.LoadModule(rootModule)
app.Listen(":3000")
}
storage.NewStorage() only receives storage.Config. It does not read environment variables itself and it does not require a manual app.RegisterSingleton(...) call.
Optional DI Registration
If a provider should receive *storage.Storage through Nika's DI container, use storage.Setup() instead:
store, err := storage.Setup(app, storage.Config{
Endpoint: cfg.GetString("S3_ENDPOINT", ""),
Region: cfg.GetString("S3_REGION", "us-east-1"),
Bucket: cfg.GetString("S3_BUCKET", ""),
AccessKey: cfg.GetString("S3_ACCESS_KEY", ""),
SecretKey: cfg.GetString("S3_SECRET_KEY", ""),
ForcePathStyle: cfg.GetBool("S3_FORCE_PATH_STYLE", true),
PublicURL: cfg.GetString("S3_PUBLIC_URL", ""),
})
if err != nil {
panic(err)
}
_ = store
Setup() configures the same package-level default instance and registers it as *storage.Storage in the app container.
Configuration
| Field | Description | Example |
|---|---|---|
Endpoint |
S3-compatible endpoint | https://s3.amazonaws.com, http://localhost:9000 |
Region |
AWS/S3 region | us-east-1 |
Bucket |
Bucket name | media |
AccessKey |
Access key ID | minioadmin |
SecretKey |
Secret access key | minioadmin |
ForcePathStyle |
Use path-style URLs for MinIO/Garage/local S3 | true |
PublicURL |
Public CDN/base URL used by URL() |
https://cdn.example.com |
Usage
After storage.NewStorage() or storage.Setup() has run, use the package-level functions from any package:
func SaveAvatar(ctx context.Context, userID string, data []byte) (string, error) {
key := "users/" + userID + "/avatar.jpg"
if err := storage.UploadBytes(ctx, key, data, "image/jpeg"); err != nil {
return "", err
}
return storage.URL(key), nil
}
Download
Stream Download
reader, err := storage.DownloadReader(ctx, "reports/monthly.pdf")
if err != nil {
return err
}
defer reader.Close()
Delete
List
files, err := storage.List(ctx, "users/42/")
if err != nil {
return err
}
for _, file := range files {
fmt.Println(file.Key, file.Size)
}
Exists
File Type Validation
common/storage also validates uploaded files before you upload them. The
detected MIME type is read from the file bytes, not from the client-provided
header or file extension.
if err := storage.ValidateFileType(file, "image/jpeg", "image/png", "image/webp"); err != nil {
return err
}
contentType, err := storage.DetectContentType(file)
if err != nil {
return err
}
err = storage.Upload(ctx, "users/42/avatar.png", src, contentType)
Allowed types can be exact MIME types or wildcards:
Working With URLs
Functions that receive a key also accept a full URL. This lets you store the public URL in your database and later pass the same value back to Download, Delete, List, or Exists.
publicURL := storage.URL("users/42/avatar.jpg")
key := storage.KeyFromURL(publicURL)
// key == "users/42/avatar.jpg"
err := storage.Delete(ctx, publicURL)
URL() preserves path segments and escapes only the unsafe characters inside each segment, so users/42/avatar 1.jpg becomes:
Direct Instance Usage
For advanced cases, create an isolated client without replacing the package-level default:
store, err := storage.New(storage.Config{
Endpoint: "http://localhost:9000",
Region: "us-east-1",
Bucket: "media",
AccessKey: "minioadmin",
SecretKey: "minioadmin",
ForcePathStyle: true,
})
if err != nil {
panic(err)
}
err = store.UploadBytes(ctx, "tmp/file.txt", []byte("hello"), "text/plain")
Use storage.SetDefault(store) if you later want that instance to become the package-level default.
API Reference
| Function | Description |
|---|---|
NewStorage(cfg) |
Configure the package-level default storage instance |
Setup(app, cfg) |
Configure default storage and register *storage.Storage in DI |
Default() |
Return the configured default instance or an error |
MustDefault() |
Return the default instance or panic when missing |
SetDefault(store) |
Replace the package-level default instance |
Upload(ctx, key, body, contentType) |
Upload from an io.Reader |
UploadBytes(ctx, key, data, contentType) |
Upload from []byte |
Download(ctx, key) |
Download object bytes |
DownloadReader(ctx, key) |
Stream object content |
Delete(ctx, key) |
Delete an object |
List(ctx, prefix) |
List objects by prefix |
Exists(ctx, key) |
Check whether an object exists |
URL(key) |
Build a public URL from PublicURL |
KeyFromURL(value) |
Convert a URL or key to an object key |
ValidateFileType(file, allowed...) |
Validate a multipart file's detected MIME type |
DetectContentType(file) |
Detect a multipart file's MIME type from bytes |
ContentTypeAllowed(contentType, allowed...) |
Check MIME type against exact or wildcard allowed types |