-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathexperiments.go
More file actions
61 lines (53 loc) · 2.09 KB
/
experiments.go
File metadata and controls
61 lines (53 loc) · 2.09 KB
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
package httpmw
import (
"fmt"
"net/http"
"strings"
"github.com/coder/coder/v2/buildinfo"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/codersdk"
)
// RequireExperiment returns middleware that checks if all required experiments are enabled.
// If any experiment is disabled, it returns a 403 Forbidden response with details about the missing experiments.
func RequireExperiment(experiments codersdk.Experiments, requiredExperiments ...codersdk.Experiment) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for _, experiment := range requiredExperiments {
if !experiments.Enabled(experiment) {
var experimentNames []string
for _, exp := range requiredExperiments {
experimentNames = append(experimentNames, string(exp))
}
// Print a message that includes the experiment names
// even if some experiments are already enabled.
var message string
if len(requiredExperiments) == 1 {
message = fmt.Sprintf("%s functionality requires enabling the '%s' experiment.",
requiredExperiments[0].DisplayName(), requiredExperiments[0])
} else {
message = fmt.Sprintf("This functionality requires enabling the following experiments: %s",
strings.Join(experimentNames, ", "))
}
httpapi.Write(r.Context(), w, http.StatusForbidden, codersdk.Response{
Message: message,
})
return
}
}
next.ServeHTTP(w, r)
})
}
}
// RequireExperimentWithDevBypass checks if ALL the given experiments are enabled,
// but bypasses the check in development mode (buildinfo.IsDev()).
func RequireExperimentWithDevBypass(experiments codersdk.Experiments, requiredExperiments ...codersdk.Experiment) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if buildinfo.IsDev() {
next.ServeHTTP(w, r)
return
}
RequireExperiment(experiments, requiredExperiments...)(next).ServeHTTP(w, r)
})
}
}