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.
(experiments codersdk.Experiments, requiredExperiments ...codersdk.Experiment)
| 13 | // RequireExperiment returns middleware that checks if all required experiments are enabled. |
| 14 | // If any experiment is disabled, it returns a 403 Forbidden response with details about the missing experiments. |
| 15 | func RequireExperiment(experiments codersdk.Experiments, requiredExperiments ...codersdk.Experiment) func(next http.Handler) http.Handler { |
| 16 | return func(next http.Handler) http.Handler { |
| 17 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 18 | for _, experiment := range requiredExperiments { |
| 19 | if !experiments.Enabled(experiment) { |
| 20 | var experimentNames []string |
| 21 | for _, exp := range requiredExperiments { |
| 22 | experimentNames = append(experimentNames, string(exp)) |
| 23 | } |
| 24 | |
| 25 | // Print a message that includes the experiment names |
| 26 | // even if some experiments are already enabled. |
| 27 | var message string |
| 28 | if len(requiredExperiments) == 1 { |
| 29 | message = fmt.Sprintf("%s functionality requires enabling the '%s' experiment.", |
| 30 | requiredExperiments[0].DisplayName(), requiredExperiments[0]) |
| 31 | } else { |
| 32 | message = fmt.Sprintf("This functionality requires enabling the following experiments: %s", |
| 33 | strings.Join(experimentNames, ", ")) |
| 34 | } |
| 35 | |
| 36 | httpapi.Write(r.Context(), w, http.StatusForbidden, codersdk.Response{ |
| 37 | Message: message, |
| 38 | }) |
| 39 | return |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | next.ServeHTTP(w, r) |
| 44 | }) |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | // RequireExperimentWithDevBypass checks if ALL the given experiments are enabled, |
| 49 | // but bypasses the check in development mode (buildinfo.IsDev()). |
no test coverage detected