Documentation
¶
Overview ¶
Package storage accesses S3-compatible object storage (Cloudflare R2, AWS S3, MinIO, Aliyun OSS) through one generic S3 client, so switching platforms only changes configuration.
Index ¶
Examples ¶
Constants ¶
const DefaultPresignExpiry = 5 * time.Minute
DefaultPresignExpiry is the lifetime of a presigned URL when PutOptions sets none.
Variables ¶
This section is empty.
Functions ¶
func InitDefault ¶
InitDefault creates the package-level default Store from cfg. A later successful call replaces the previous default.
Types ¶
type Config ¶
type Config struct {
Endpoint string // S3 API endpoint, e.g. https://{accountId}.r2.cloudflarestorage.com
Region string // "auto" for R2
UsePathStyle bool // true for MinIO
AccessKeyID string
SecretAccessKey string
Bucket string // main bucket
ArchiveBucket string // optional second bucket, e.g. for private archived objects
PublicBaseURL string // optional public URL prefix of Bucket, without a trailing slash
}
Config holds the settings of an S3-compatible object store. The caller is responsible for reading values from env (or any other source) at the composition root so this package has no dependency on env; storage/component does that for the storage.* keys.
The fields carry no platform name: Cloudflare R2, AWS S3, MinIO and Aliyun OSS differ only in their values.
func (Config) Validate ¶
Validate reports the first required field that is empty, or a conflict between Bucket and ArchiveBucket.
Example ¶
ExampleConfig_Validate shows the error for a missing required field.
package main
import (
"fmt"
"github.com/phcp-tech/common-library-golang/storage"
)
func main() {
err := storage.Config{Endpoint: "https://s3.example.com", Region: "auto"}.Validate()
fmt.Println(err)
}
Output: storage: AccessKeyID is required
type PresignedPut ¶ added in v0.2.2
PresignedPut is an upload URL and the headers the PUT request must send.
type PutOptions ¶ added in v0.2.2
type PutOptions struct {
ContentType string // required
Size int64 // required: the exact body size in bytes
CacheControl string // optional
ContentDisposition string // optional; empty: no header, browsers show the file inline
Metadata map[string]string // optional x-amz-meta-* values, e.g. {"uploader-id": "7"}
Expires time.Duration // optional; 0: DefaultPresignExpiry
}
PutOptions are the object headers a presigned upload signs. The client must send every one of them, as returned in PresignedPut.Headers.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is an S3 client bound to the buckets of one Config.
func Default ¶
func Default() *Store
Default returns the package-level default Store, or nil before InitDefault succeeds. Use New for any other instance.
func New ¶
New validates cfg and creates the S3 client. It does not contact the store; call Check for that.
Example ¶
ExampleNew shows how to create a Store for Cloudflare R2. The caller reads configuration from env (or any other source) at the composition root — this package has no dependency on env. New does not contact the store.
package main
import (
"fmt"
"github.com/phcp-tech/common-library-golang/storage"
)
func main() {
s, err := storage.New(storage.Config{
Endpoint: "https://account-id.r2.cloudflarestorage.com",
Region: "auto",
AccessKeyID: "access-key-id",
SecretAccessKey: "secret-access-key",
Bucket: "zhishi-content-dev",
ArchiveBucket: "zhishi-archive-dev", // optional
PublicBaseURL: "https://dev.content.zhishi.io",
})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(s.Config().Bucket)
}
Output: zhishi-content-dev
Example (Minio) ¶
ExampleNew_minio shows the only difference for MinIO: path-style URLs.
package main
import (
"fmt"
"github.com/phcp-tech/common-library-golang/storage"
)
func main() {
s, err := storage.New(storage.Config{
Endpoint: "http://127.0.0.1:9000",
Region: "us-east-1",
UsePathStyle: true,
AccessKeyID: "minioadmin",
SecretAccessKey: "minioadmin",
Bucket: "content",
})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(s.Config().UsePathStyle)
}
Output: true
func (*Store) Check ¶
Check verifies that every configured bucket is reachable with the credentials. It lists at most one object per bucket, which a token limited to object read/write is allowed to do.
Example ¶
ExampleStore_Check verifies that every configured bucket is reachable. A local stand-in answers ListObjectsV2 here; in production the endpoint is R2, S3, MinIO or OSS.
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"github.com/phcp-tech/common-library-golang/storage"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
bucket := strings.Trim(r.URL.Path, "/")
w.Header().Set("Content-Type", "application/xml")
fmt.Fprintf(w, `<ListBucketResult><Name>%s</Name><KeyCount>0</KeyCount></ListBucketResult>`, bucket)
}))
defer srv.Close()
s, err := storage.New(storage.Config{
Endpoint: srv.URL,
Region: "us-east-1",
UsePathStyle: true,
AccessKeyID: "id",
SecretAccessKey: "secret",
Bucket: "content",
ArchiveBucket: "archive",
})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(s.Check(context.Background()))
}
Output: <nil>
func (*Store) Client ¶
Client returns the underlying S3 client for operations this package does not wrap.
Example ¶
ExampleStore_Client shows how to call an S3 operation that Store does not wrap, for example writing an immutable public object.
package main
import (
"context"
"fmt"
"strings"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/phcp-tech/common-library-golang/storage"
)
func main() {
s := storage.Default() // set by storage/component, or call storage.New
if s == nil {
return
}
_, err := s.Client().PutObject(context.Background(), &s3.PutObjectInput{
Bucket: aws.String(s.Config().Bucket),
Key: aws.String("articles/2026/11/GeryF6t32aARmCEW/r3.md"),
Body: strings.NewReader("# Title\n"),
ContentType: aws.String("text/markdown; charset=utf-8"),
CacheControl: aws.String("public, max-age=31536000, immutable"),
})
if err != nil {
fmt.Println(err)
}
}
Output:
func (*Store) PresignPut ¶ added in v0.2.2
func (s *Store) PresignPut(ctx context.Context, key string, o PutOptions) (PresignedPut, error)
PresignPut returns a URL that uploads one object to key in the main bucket (Config.Bucket) with a plain HTTP PUT, e.g. straight from a browser. It does not contact the store.