Files
coder/coderd/httpmw/templateparam.go
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

52 lines
1.5 KiB
Go
Raw Normal View History

2022-04-06 12:42:40 -05:00
package httpmw
import (
"context"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/codersdk"
2022-04-06 12:42:40 -05:00
)
type templateParamContextKey struct{}
// TemplateParam returns the template from the ExtractTemplateParam handler.
func TemplateParam(r *http.Request) database.Template {
template, ok := r.Context().Value(templateParamContextKey{}).(database.Template)
if !ok {
panic("developer error: template param middleware not provided")
}
return template
}
// ExtractTemplateParam grabs a template from the "template" URL parameter.
func ExtractTemplateParam(db database.Store) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
2022-09-21 17:07:00 -05:00
ctx := r.Context()
templateID, parsed := ParseUUIDParam(rw, r, "template")
2022-04-06 12:42:40 -05:00
if !parsed {
return
}
template, err := db.GetTemplateByID(r.Context(), templateID)
if httpapi.Is404Error(err) || (err == nil && template.Deleted) {
2022-06-14 10:14:05 -05:00
httpapi.ResourceNotFound(rw)
return
2022-04-06 12:42:40 -05:00
}
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error fetching template.",
Detail: err.Error(),
2022-04-06 12:42:40 -05:00
})
return
}
2022-09-21 17:07:00 -05:00
ctx = context.WithValue(ctx, templateParamContextKey{}, template)
2022-04-06 12:42:40 -05:00
chi.RouteContext(ctx).URLParams.Add("organization", template.OrganizationID.String())
next.ServeHTTP(rw, r.WithContext(ctx))
})
}
}