MCPcopy
hub / github.com/go-chi/chi / ArticleCtx

Function ArticleCtx

_examples/rest/main.go:124–145  ·  view source on GitHub ↗

ArticleCtx middleware is used to load an Article object from the URL parameters passed through as the request. In case the Article could not be found, we stop here and return a 404.

(next http.Handler)

Source from the content-addressed store, hash-verified

122// the URL parameters passed through as the request. In case
123// the Article could not be found, we stop here and return a 404.
124func ArticleCtx(next http.Handler) http.Handler {
125 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
126 var article *Article
127 var err error
128
129 if articleID := chi.URLParam(r, "articleID"); articleID != "" {
130 article, err = dbGetArticle(articleID)
131 } else if articleSlug := chi.URLParam(r, "articleSlug"); articleSlug != "" {
132 article, err = dbGetArticleBySlug(articleSlug)
133 } else {
134 render.Render(w, r, ErrNotFound)
135 return
136 }
137 if err != nil {
138 render.Render(w, r, ErrNotFound)
139 return
140 }
141
142 ctx := context.WithValue(r.Context(), "article", article)
143 next.ServeHTTP(w, r.WithContext(ctx))
144 })
145}
146
147// SearchArticles searches the Articles data for a matching article.
148// It's just a stub, but you get the idea.

Callers

nothing calls this directly

Calls 6

dbGetArticleFunction · 0.85
dbGetArticleBySlugFunction · 0.85
HandlerFuncMethod · 0.80
URLParamMethod · 0.80
RenderMethod · 0.45
ServeHTTPMethod · 0.45

Tested by

no test coverage detected