curcuma

ref: master

./server.go


 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package curcuma

import (
	"io"
	"mime"
	"path"
	"log"
	"fmt"

	"net/http"
	"github.com/go-chi/chi/v5"
	"github.com/minio/minio-go/v7"
	"github.com/vaughan0/go-ini"
)

type Server struct {
	MinioClient *minio.Client
	Config ini.File
}

func NewServer(mc *minio.Client, config ini.File) (*Server) {
	return &Server{
		MinioClient: mc,
		Config: config,
	}
}

func (s *Server) Start() {
	router := chi.NewRouter()

	router.Get("/*", func(w http.ResponseWriter, r *http.Request) {
		s3Path := chi.URLParam(r, "*")
		mc := s.MinioClient
		bucketName, _ := s.Config.Get("s3", "bucket")

		// XXX: We shouldn't just apply the route blindly
		var (
			object *minio.Object
			err error
		)

		_, err = mc.StatObject(r.Context(), bucketName, s3Path, minio.StatObjectOptions{})
		if err != nil {
			log.Printf("404 on Stats")
			w.WriteHeader(404)
			w.Write([]byte("404 Not Found \n"))

			return
		}

		object, err = mc.GetObject(r.Context(), bucketName, s3Path, minio.GetObjectOptions{})

		if err != nil {
			log.Printf("500 on Fetching Object, %s", err)
			w.WriteHeader(500)
			w.Write([]byte("500 There was an Internal Error\n"))

			return
		}

		if object == nil {
			log.Printf("404 after Fetching Object")
			w.WriteHeader(404)
			w.Write([]byte("404 Not Found \n"))

			return
		}

		defer object.Close()
		mimetype := mime.TypeByExtension(path.Ext(s3Path))

		if mimetype != "" {
			w.Header().Add("Content-Type", mimetype)
		}

		if _, err := io.Copy(w, object); err != nil {
			w.WriteHeader(500)
			w.Write([]byte(fmt.Sprintf("%s \n", err)))
		}
	})

	addr, _ := s.Config.Get("meta", "port")
	if addr == "" {
		addr = ":8100"
	}

	http.ListenAndServe(addr, router)
}