| 53 | var routes = flag.Bool("routes", false, "Generate router documentation") |
| 54 | |
| 55 | func main() { |
| 56 | flag.Parse() |
| 57 | |
| 58 | r := chi.NewRouter() |
| 59 | |
| 60 | r.Use(middleware.RequestID) |
| 61 | r.Use(middleware.Logger) |
| 62 | r.Use(middleware.Recoverer) |
| 63 | r.Use(middleware.URLFormat) |
| 64 | r.Use(render.SetContentType(render.ContentTypeJSON)) |
| 65 | |
| 66 | r.Get("/", func(w http.ResponseWriter, r *http.Request) { |
| 67 | w.Write([]byte("root.")) |
| 68 | }) |
| 69 | |
| 70 | r.Get("/ping", func(w http.ResponseWriter, r *http.Request) { |
| 71 | w.Write([]byte("pong")) |
| 72 | }) |
| 73 | |
| 74 | r.Get("/panic", func(w http.ResponseWriter, r *http.Request) { |
| 75 | panic("test") |
| 76 | }) |
| 77 | |
| 78 | // RESTy routes for "articles" resource |
| 79 | r.Route("/articles", func(r chi.Router) { |
| 80 | r.With(paginate).Get("/", ListArticles) |
| 81 | r.Post("/", CreateArticle) // POST /articles |
| 82 | r.Get("/search", SearchArticles) // GET /articles/search |
| 83 | |
| 84 | r.Route("/{articleID}", func(r chi.Router) { |
| 85 | r.Use(ArticleCtx) // Load the *Article on the request context |
| 86 | r.Get("/", GetArticle) // GET /articles/123 |
| 87 | r.Put("/", UpdateArticle) // PUT /articles/123 |
| 88 | r.Delete("/", DeleteArticle) // DELETE /articles/123 |
| 89 | }) |
| 90 | |
| 91 | // GET /articles/whats-up |
| 92 | r.With(ArticleCtx).Get("/{articleSlug:[a-z-]+}", GetArticle) |
| 93 | }) |
| 94 | |
| 95 | // Mount the admin sub-router, which btw is the same as: |
| 96 | // r.Route("/admin", func(r chi.Router) { admin routes here }) |
| 97 | r.Mount("/admin", adminRouter()) |
| 98 | |
| 99 | // Passing -routes to the program will generate docs for the above |
| 100 | // router definition. See the `routes.json` file in this folder for |
| 101 | // the output. |
| 102 | if *routes { |
| 103 | // fmt.Println(docgen.JSONRoutesDoc(r)) |
| 104 | fmt.Println(docgen.MarkdownRoutesDoc(r, docgen.MarkdownOpts{ |
| 105 | ProjectPath: "github.com/go-chi/chi/v5", |
| 106 | Intro: "Welcome to the chi/_examples/rest generated docs.", |
| 107 | })) |
| 108 | return |
| 109 | } |
| 110 | |
| 111 | http.ListenAndServe(":3333", r) |
| 112 | } |