-
Notifications
You must be signed in to change notification settings - Fork 67
/
package_index.go
91 lines (76 loc) · 2.65 KB
/
package_index.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
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package main
import (
"errors"
"net/http"
"time"
"go.elastic.co/apm/module/apmzap/v2"
"go.uber.org/zap"
"github.com/Masterminds/semver/v3"
"github.com/gorilla/mux"
"github.com/elastic/package-registry/internal/util"
"github.com/elastic/package-registry/packages"
"github.com/elastic/package-registry/proxymode"
)
const (
packageIndexRouterPath = "/package/{packageName:[a-z0-9_]+}/{packageVersion}/"
)
var errPackageRevisionNotFound = errors.New("package revision not found")
func packageIndexHandler(logger *zap.Logger, indexer Indexer, cacheTime time.Duration) func(w http.ResponseWriter, r *http.Request) {
return packageIndexHandlerWithProxyMode(logger, indexer, proxymode.NoProxy(logger), cacheTime)
}
func packageIndexHandlerWithProxyMode(logger *zap.Logger, indexer Indexer, proxyMode *proxymode.ProxyMode, cacheTime time.Duration) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
logger := logger.With(apmzap.TraceContext(r.Context())...)
vars := mux.Vars(r)
packageName, ok := vars["packageName"]
if !ok {
badRequest(w, "missing package name")
return
}
packageVersion, ok := vars["packageVersion"]
if !ok {
badRequest(w, "missing package version")
return
}
_, err := semver.StrictNewVersion(packageVersion)
if err != nil {
badRequest(w, "invalid package version")
return
}
opts := packages.NameVersionFilter(packageName, packageVersion)
pkgs, err := indexer.Get(r.Context(), &opts)
if err != nil {
logger.Error("getting package path failed", zap.Error(err))
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
if len(pkgs) == 0 && proxyMode.Enabled() {
proxiedPackage, err := proxyMode.Package(r)
if err != nil {
logger.Error("proxy mode: package failed", zap.Error(err))
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
if proxiedPackage != nil {
pkgs = pkgs.Join(packages.Packages{proxiedPackage})
}
}
if len(pkgs) == 0 {
notFoundError(w, errPackageRevisionNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
cacheHeaders(w, cacheTime)
err = util.WriteJSONPretty(w, pkgs[0])
if err != nil {
logger.Error("marshaling package index failed",
zap.String("package.path", pkgs[0].BasePath),
zap.Error(err))
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
}
}