-
Notifications
You must be signed in to change notification settings - Fork 0
/
web_server.go
93 lines (78 loc) · 2.35 KB
/
web_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
89
90
91
92
93
package web
import (
"fmt"
"github.com/materials-commons/config"
"github.com/materials-commons/mcfs/base/log"
"github.com/materials-commons/mcfs/server/request"
"github.com/materials-commons/mcfs/server/servers"
"github.com/materials-commons/mcfs/server/service"
"mime"
"net/http"
"path/filepath"
"strings"
)
type webServer struct{}
var l = log.New("server", "WebServer")
var server = &webServer{}
var mcdir = config.GetString("MCDIR")
func Server() servers.Instance {
return server
}
func (s *webServer) Init() {
}
func (s *webServer) Run(stopChan <-chan struct{}) {
go s.webserver()
<-stopChan
}
func (s *webServer) webserver() {
port := config.GetInt("MCFS_HTTP_PORT")
http.HandleFunc("/datafiles/static/", s.datafileHandler)
err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
var _ = err
}
func (s *webServer) datafileHandler(writer http.ResponseWriter, req *http.Request) {
apikey := req.FormValue("apikey")
if apikey == "" {
http.Error(writer, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
download := req.FormValue("download")
// Verify key
u, err := service.User.ByAPIKey(apikey)
if err != nil {
http.Error(writer, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
// Get datafile from db and check access
dataFileID := filepath.Base(req.URL.Path)
df, err := service.File.ByID(dataFileID)
switch {
case err != nil:
http.Error(writer, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
case !service.Group.HasAccess(df.Owner, u.Email):
http.Error(writer, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
default:
var path string
if isTiff(df.Name) && download == "" {
path = tiffConversionPath(mcdir, df.FileID())
} else {
extension := strings.ToLower(filepath.Ext(df.Name))
if mimetype := mime.TypeByExtension(extension); mimetype != "" {
writer.Header().Set("Content-Type", mimetype)
}
path = request.DataFilePath(mcdir, df.FileID())
}
http.ServeFile(writer, req, path)
}
}
// isTiff checks a name to see if it is for a TIFF file.
func isTiff(name string) bool {
ext := strings.ToLower(filepath.Ext(name))
if ext == ".tiff" || ext == ".tif" {
return true
}
return false
}
func tiffConversionPath(mcdir, id string) string {
return filepath.Join(request.DataFileDir(mcdir, id), ".conversion", id+".jpg")
}