package s3
import (
"context"
"errors"
"net/http"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/vaughan0/go-ini"
)
var minioCtxKey = &contextKey{"minio"}
type contextKey struct {
name string
}
func Middleware(client *minio.Client) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := Context(r.Context(), client)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
}
func Context(ctx context.Context, client *minio.Client) context.Context {
return context.WithValue(ctx, minioCtxKey, client)
}
func ForContext(ctx context.Context) *minio.Client {
raw, ok := ctx.Value(minioCtxKey).(*minio.Client)
if !ok {
panic("Invalid minio context")
}
return raw
}
var ErrDisabled = errors.New("object storage is not enabled for this server")
func NewClient(conf ini.File) (*minio.Client, error) {
upstream, _ := conf.Get("objects", "s3-upstream")
accessKey, _ := conf.Get("objects", "s3-access-key")
secretKey, _ := conf.Get("objects", "s3-secret-key")
if upstream == "" || accessKey == "" || secretKey == "" {
return nil, ErrDisabled
}
return minio.New(upstream, &minio.Options{
Creds: credentials.NewStaticV4(accessKey, secretKey, ""),
Secure: true,
})
}
func URL(conf ini.File, bucket string) string {
upstream, _ := conf.Get("objects", "s3-upstream")
if upstream == "" {
return ""
}
return "https://" + upstream
}