~bigbes/core-go

ref: 23808bb0998277ff986660ce21c97b2dc88139a9 core-go/s3/middleware.go -rw-r--r-- 1.7 KiB
23808bb0 — Simon Ser auth: add RequireMiddleware 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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")
	insecure, _ := conf.Get("objects", "s3-insecure")
	if upstream == "" || accessKey == "" || secretKey == "" {
		return nil, ErrDisabled
	}

	return minio.New(upstream, &minio.Options{
		Creds:  credentials.NewStaticV4(accessKey, secretKey, ""),
		Secure: insecure != "yes",
	})
}

func URL(conf ini.File, bucket string) string {
	upstream, _ := conf.Get("objects", "s3-upstream")
	insecure, _ := conf.Get("objects", "s3-insecure")
	if upstream == "" {
		return ""
	}

	proto := "https"
	if insecure == "yes" {
		proto = "http"
	}

	return proto + "://" + upstream
}