ExtractTemplateParam grabs a template from the "template" URL parameter.
(db database.Store)
| 24 | |
| 25 | // ExtractTemplateParam grabs a template from the "template" URL parameter. |
| 26 | func ExtractTemplateParam(db database.Store) func(http.Handler) http.Handler { |
| 27 | return func(next http.Handler) http.Handler { |
| 28 | return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { |
| 29 | ctx := r.Context() |
| 30 | templateID, parsed := ParseUUIDParam(rw, r, "template") |
| 31 | if !parsed { |
| 32 | return |
| 33 | } |
| 34 | template, err := db.GetTemplateByID(r.Context(), templateID) |
| 35 | if httpapi.Is404Error(err) || (err == nil && template.Deleted) { |
| 36 | httpapi.ResourceNotFound(rw) |
| 37 | return |
| 38 | } |
| 39 | if err != nil { |
| 40 | httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ |
| 41 | Message: "Internal error fetching template.", |
| 42 | Detail: err.Error(), |
| 43 | }) |
| 44 | return |
| 45 | } |
| 46 | |
| 47 | ctx = context.WithValue(ctx, templateParamContextKey{}, template) |
| 48 | chi.RouteContext(ctx).URLParams.Add("organization", template.OrganizationID.String()) |
| 49 | next.ServeHTTP(rw, r.WithContext(ctx)) |
| 50 | }) |
| 51 | } |
| 52 | } |