<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ryan Lee on Medium]]></title>
        <description><![CDATA[Stories by Ryan Lee on Medium]]></description>
        <link>https://medium.com/@printSAN0?source=rss-722d3ae17c9c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*BV6ejwk-Qd7pvOVF</url>
            <title>Stories by Ryan Lee on Medium</title>
            <link>https://medium.com/@printSAN0?source=rss-722d3ae17c9c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:16:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@printSAN0/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Automating SwaggerUI for Go-Chi Router without Swaggo (Part 1)]]></title>
            <link>https://medium.com/@printSAN0/automating-swaggerui-for-go-chi-router-without-swaggo-part-1-032698239f2a?source=rss-722d3ae17c9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/032698239f2a</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[swaggo]]></category>
            <category><![CDATA[swagger]]></category>
            <dc:creator><![CDATA[Ryan Lee]]></dc:creator>
            <pubDate>Sat, 04 Nov 2023 09:03:24 GMT</pubDate>
            <atom:updated>2023-11-05T06:51:22.091Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro</h3><p>Ever since I was introduced to Go Lang, I fell in love with its simplicity and fast performance. Lately, I have been creating a boilerplate for APIs by using Go Lang, specifically Go-Chi router. While creating a boilerplate, I needed a method to document my API. When I created APIs in Java Spring or Python Django, I always used Swagger UI to document my API. Upon searching modules, I found that swaggo/http-swagger was one of the popular ones used by developers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*ioP9ZI9GLDtWyNLu.png" /><figcaption>image source: <a href="https://github.com/swaggo/swag">https://github.com/swaggo/swag</a></figcaption></figure><h3>Problem</h3><p>Upon looking at the documentation and examples, the way it is used made my eyes cringe. It was very different from Swagger UI used in Django or Spring. Below is an example of how to use Swagger UI in Django.</p><p>Although there are much more than this, but it boils down to these specific lines when creating Swagger UI in Django.</p><pre>schema_view = get_schema_view(title=&quot;title&quot;)<br><br>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&quot;&quot;,include(&quot;app.urls&quot;)),<br>    path(&#39;docs/&#39;, schema_view.with_ui(&#39;swagger&#39;, cache_timeout=0),name=&#39;schema-swagger-ui&#39;),<br><br>]</pre><ul><li>code source: <a href="https://django-rest-swagger.readthedocs.io/en/latest/">https://django-rest-swagger.readthedocs.io/en/latest/</a></li></ul><p>You will have to add paths in urlpatterns for paths declared in the app but that is not a lot of work.</p><p>But now, look at the example on swaggo/http-swagger.</p><pre>package main<br><br>import (<br> &quot;net/http&quot;<br><br> &quot;github.com/go-chi/chi&quot;<br> &quot;github.com/swaggo/http-swagger/v2&quot;<br> _ &quot;github.com/swaggo/http-swagger/example/go-chi/docs&quot; // docs is generated by Swag CLI, you have to import it.<br>)<br><br>// @title Swagger Example API<br>// @version 1.0<br>// @description This is a sample server Petstore server.<br>// @termsOfService http://swagger.io/terms/<br><br>// @contact.name API Support<br>// @contact.url http://www.swagger.io/support<br>// @contact.email support@swagger.io<br><br>// @license.name Apache 2.0<br>// @license.url http://www.apache.org/licenses/LICENSE-2.0.html<br><br>// @host petstore.swagger.io<br>// @BasePath /v2<br>func main() {<br> r := chi.NewRouter()<br><br> r.Get(&quot;/swagger/*&quot;, httpSwagger.Handler(<br>  httpSwagger.URL(&quot;http://localhost:1323/swagger/doc.json&quot;), //The url pointing to API definition<br> ))<br><br> http.ListenAndServe(&quot;:1323&quot;, r)<br>}</pre><ul><li>code source: <a href="https://github.com/swaggo/http-swagger">https://github.com/swaggo/http-swagger</a></li></ul><p>And to add information regarding each routes or paths, the following needs to be added.</p><pre>// GetOrders godoc<br>// @Summary Get details of all orders<br>// @Description Get details of all orders<br>// @Tags orders<br>// @Accept  json<br>// @Produce  json<br>// @Success 200 {array} Order<br>// @Router /orders [get]<br>func getOrders(w http.ResponseWriter, r *http.Request) {<br>    w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>    json.NewEncoder(w).Encode(orders)<br>}</pre><ul><li>code source: <a href="https://www.soberkoder.com/swagger-go-api-swaggo/">https://www.soberkoder.com/swagger-go-api-swaggo/</a></li></ul><p>Upon seeing all of these comments on top of each methods, I was just shocked. One, I am way too lazy (for real) to write out all of that just a single endpoint. Two, why even create a Swagger UI with all of those information? Might as well just write it down on a piece paper and show it to everyone. Nothing was “automated” in this swagger module.</p><h3>Solution</h3><p>So while working on the API boilerplate, I decided to make a true (partial) automated Swagger UI generator for my boilerplate.</p><blockquote>Before reading the rest of the post, I am just a student who loves coding and what I say here might not be correct. I might not have the best coding habits. I am still fairly new to Go Lang. In this post (part 1), I have only accomplished certain parts of the Swagger UI generation.</blockquote><h4>First, below are the routes I have in my boilerplate.</h4><pre>package routes<br><br>import (<br> &quot;log&quot;<br><br> &quot;github.com/go-chi/chi/v5&quot;<br> &quot;github.com/go-chi/chi/v5/middleware&quot;<br> &quot;github.com/printSANO/gorest-boilerplate/cmd/handlers&quot;<br> &quot;github.com/printSANO/gorest-boilerplate/config&quot;<br>)<br><br>func NewRouter(port string, basePath string) *chi.Mux {<br> r := chi.NewRouter()<br><br> config.BasePath = basePath<br><br> r.Use(middleware.RequestID)<br> r.Use(middleware.RealIP)<br> r.Use(middleware.Logger)<br> r.Use(middleware.Recoverer)<br><br> r.Route(basePath, func(r chi.Router) {<br>  userRouter(r)<br>  reviewRouter(r)<br>  movieRouter(r)<br> })<br><br> log.Println(&quot;Server is running on port&quot;, port)<br><br> return r<br>}<br><br>func userRouter(r chi.Router) {<br> r.Route(&quot;/users&quot;, func(r chi.Router) {<br>  r.Use(handlers.UserCtx)<br>  r.Get(&quot;/&quot;, handlers.GetUsers)<br>  r.Get(&quot;/{id}&quot;, handlers.GetUser)<br>  r.Post(&quot;/&quot;, handlers.CreateUser)<br>  r.Put(&quot;/{id}&quot;, handlers.UpdateUser)<br>  r.Delete(&quot;/{id}&quot;, handlers.DeleteUser)<br> })<br>}<br><br>func reviewRouter(r chi.Router) {<br> r.Route(&quot;/reviews&quot;, func(r chi.Router) {<br>  r.Use(handlers.ReviewCtx)<br>  r.Get(&quot;/&quot;, handlers.GetReviews)<br>  r.Get(&quot;/{id}&quot;, handlers.GetReview)<br>  r.Post(&quot;/&quot;, handlers.CreateReview)<br>  r.Put(&quot;/{id}&quot;, handlers.UpdateReview)<br>  r.Delete(&quot;/{id}&quot;, handlers.DeleteReview)<br> })<br>}<br><br>func movieRouter(r chi.Router) {<br> r.Route(&quot;/movies&quot;, func(r chi.Router) {<br>  r.Use(handlers.MovieCtx)<br>  r.Get(&quot;/&quot;, handlers.GetMovies)<br>  r.Get(&quot;/{id}&quot;, handlers.GetMovie)<br>  r.Post(&quot;/&quot;, handlers.CreateMovie)<br>  r.Put(&quot;/{id}&quot;, handlers.UpdateMovie)<br>  r.Delete(&quot;/{id}&quot;, handlers.DeleteMovie)<br> })<br>}</pre><p>I have users, reviews, and movies paths with different methods in each paths. Then they are all added in basePath route which is “/api/v1” in my case.</p><p>With the above information, I would have to create swagger.json with the following criteria.</p><ul><li>swaggerUI version (fixed at 2.0)</li><li>API description</li><li>contact information</li><li>license information</li><li>API version</li><li>host</li><li>base path</li><li>paths</li></ul><p>Within paths, there needs to be way more information such as methods, parameters, descriptions, and etc but I will start here.</p><h4>To fulfill those requirements, I made a function to initialize swagger ui.</h4><pre>// below is a part of our main.go<br>r := routes.NewRouter(config.NewPortConfig(), &quot;/api/v1&quot;)<br> info := swagger.Info{<br>  Description: &quot;This is a testing API&quot;,<br>  Title:       &quot;test API&quot;,<br>  Contact:     swagger.Contacts{},<br>  Version:     &quot;1&quot;,<br> }<br> swagger.GenerateDoc(r, &quot;localhost&quot;, info)</pre><p>The routes.NewRouter function creates a new go-chi router with base path “/api/v1” and passes the *chi.Mux object to swagger.GenerateDoc alongside with info struct which holds the requirements I mentioned above and host.</p><h4>Now if you look at part of my GenerateDoc function, it has..</h4><pre>func GenerateDoc(r *chi.Mux, host string, info Info) {<br> pathsInfo, _ := generateEnpointMap(r)<br> st := SwaggerTemplate{<br>  Version:     &quot;2.0&quot;,<br>  SwaggerInfo: info,<br>  Host:        host,<br>  BasePath:    config.BasePath,<br>  Paths:       pathsInfo,<br> }<br>//<br>//more code..<br>}<br><br>type SwaggerTemplate struct {<br> Version     string    `json:&quot;swagger&quot;`<br> SwaggerInfo Info      `json:&quot;info&quot;`<br> Host        string    `json:&quot;host&quot;`<br> BasePath    string    `json:&quot;basePath&quot;`<br> Paths       MapMethod `json:&quot;paths&quot;`<br>}<br><br>type Info struct {<br> Description string   `json:&quot;description&quot;`<br> Title       string   `json:&quot;title&quot;`<br> Contact     Contacts `json:&quot;contact&quot;`<br> License     Licenses `json:&quot;license,omitempty&quot;`<br> Version     string   `json:&quot;version&quot;`<br>}<br><br>type Contacts struct {<br> Name  string `json:&quot;name,omitempty&quot;`<br> URL   string `json:&quot;url,omitempty&quot;`<br> Email string `json:&quot;email,omitempty&quot;`<br>}<br><br>type Licenses struct {<br> Name string `json:&quot;name,omitempty&quot;`<br> URL  string `json:&quot;url,omitempty&quot;`<br>}</pre><p>The SwaggerTemplate struct creates the desired requirements talked about in a very simple way.</p><h4>The result of the SwaggerTemplate looks like this in swagger.json.</h4><pre>{<br> &quot;swagger&quot;: &quot;2.0&quot;,<br> &quot;info&quot;: {<br> &quot;description&quot;: &quot;This is a testing API&quot;,<br> &quot;title&quot;: &quot;test API&quot;,<br> &quot;contact&quot;: {},<br> &quot;license&quot;: {},<br> &quot;version&quot;: &quot;1&quot;<br> },<br> &quot;host&quot;: &quot;localhost&quot;,<br> &quot;basePath&quot;: &quot;/api/v1&quot;,<br> &quot;paths&quot;: {}<br>}</pre><p>Now the basic part of Swagger UI is taken care of, now becomes the real deal.</p><blockquote>How can I extract path and method information from go-chi router?</blockquote><p>If you looked closely, you can see that paths are created by a function generateEnpointMap(r). Then lets look at that function… and buildSwagerPaths since that is what’s important</p><pre>// i separated some functions for future purposes<br>func generateEnpointMap(r *chi.Mux) (MapMethod, error) {<br> p := buildSwaggerPaths(r)<br><br> return p, nil<br>}<br>func buildSwaggerPaths(r *chi.Mux) MapMethod {<br> rts := r<br> mm := MapMethod{}<br> paths := buildRoutes(rts, mm, &quot;&quot;, config.BasePath)<br><br> return paths<br>}<br>func buildRoutes(r chi.Routes, m MapMethod, pattern string, basePath string) MapMethod {<br> for _, rt := range r.Routes() {<br>  var currentPattern string<br>  if rt.Pattern != &quot;/&quot; {<br>   currentPattern = pattern + rt.Pattern<br>  } else {<br>   currentPattern = pattern<br>  }<br>  temp := strings.Replace(currentPattern, &quot;/*&quot;, &quot;&quot;, 2)<br>  if temp != basePath {<br>   routeMethods := make(MethodInfos)<br>   for method, _ := range rt.Handlers {<br>    methodInfoTemp := MethodInfo{Description: &quot;test&quot;}<br>    routeMethods[strings.ToLower(method)] = methodInfoTemp<br>   }<br>   m[strings.Replace(temp, basePath, &quot;&quot;, 1)] = routeMethods<br>  }<br><br>  if rt.SubRoutes != nil {<br>   buildRoutes(rt.SubRoutes, m, currentPattern, basePath)<br>  }<br> }<br> return m<br>}</pre><p>And below are the structs used in creating the paths.</p><pre>type Path struct {<br> Paths MapMethod `json:&quot;paths&quot;`<br>}<br><br>type MapMethod map[string]MethodInfos<br><br>type MethodInfos map[string]MethodInfo<br><br>type MethodInfo struct {<br> Description string      `json:&quot;description,omitempty&quot;`<br> Consumes    []string    `json:&quot;consumes,omitempty&quot;`<br> Produces    []string    `json:&quot;produces,omitempty&quot;`<br> Tags        []string    `json:&quot;tags,omitempty&quot;`<br> Parameters  []Parameter `json:&quot;parameters,omitempty&quot;`<br> Responses   Response    `json:&quot;responses,omitempty&quot;`<br>}<br><br>type Parameter struct {<br> Type        string    `json:&quot;type,omitempty&quot;`<br> Description string    `json:&quot;description,omitempty&quot;`<br> Name        string    `json:&quot;name,omitempty&quot;`<br> In          string    `json:&quot;in,omitempty&quot;`<br> Required    string    `json:&quot;required,omitempty&quot;`<br> Schema      ResSchema `json:&quot;schema,omitempty&quot;`<br>}<br><br>type Response map[string]Parameter<br><br>type ResSchema struct {<br> Type                 string `json:&quot;type,omitempty&quot;`<br> Items                Item   `json:&quot;items,omitempty&quot;`<br> AdditionalProperties bool   `json:&quot;additionalProperties,omitempty&quot;`<br>}<br><br>type Item struct {<br> Ref string `json:&quot;$ref,omitempty&quot;`<br>}</pre><p>So the function buildRoutes is the main algorithm for building swagger paths in a json format. The function uses recursion to iterate through r.Routes() which is an array of chi.Routes. Every chi.Route contains handlers, pattern, and subRoutes. SubRoutes are also an array of chi.Routes. Pattern contains the current endpoint pattern, handlers contain the handler method (function) that is involved with the current endpoint. I will not go too deeply into handlers for part 1.</p><p>By using pattern and subRoutes, I was able to extract paths from chi.Route and created a MapMethod struct containing patterns and methods. Handlers were used to extract the methods (get, post, put, etc) associated with each endpoint because rt.Handlers is a map of http method and handler (ex. map[”get”]http.Handler).</p><h4>With the functions above, I was able to create swagger.json that looks like this:</h4><pre>{<br> &quot;swagger&quot;: &quot;2.0&quot;,<br> &quot;info&quot;: {<br>  &quot;description&quot;: &quot;This is a testing API&quot;,<br>  &quot;title&quot;: &quot;test API&quot;,<br>  &quot;contact&quot;: {},<br>  &quot;license&quot;: {},<br>  &quot;version&quot;: &quot;1&quot;<br> },<br> &quot;host&quot;: &quot;localhost&quot;,<br> &quot;basePath&quot;: &quot;/api/v1&quot;,<br> &quot;paths&quot;: {<br>  &quot;/movies&quot;: {<br>   &quot;get&quot;: {<br>    &quot;description&quot;: &quot;test&quot;<br>   },<br>   &quot;post&quot;: {<br>    &quot;description&quot;: &quot;test&quot;<br>   }<br>  },<br>  &quot;/movies/{id}&quot;: {<br>   &quot;delete&quot;: {<br>    &quot;description&quot;: &quot;test&quot;<br>   },<br>   &quot;get&quot;: {<br>    &quot;description&quot;: &quot;test&quot;<br>   },<br>   &quot;put&quot;: {<br>    &quot;description&quot;: &quot;test&quot;<br>   }<br>  },<br>  &quot;/reviews&quot;: {<br>   &quot;get&quot;: {<br>    &quot;description&quot;: &quot;test&quot;<br>   },<br>   &quot;post&quot;: {<br>    &quot;description&quot;: &quot;test&quot;<br>   }<br>  },<br>  &quot;/reviews/{id}&quot;: {<br>   &quot;delete&quot;: {<br>    &quot;description&quot;: &quot;test&quot;<br>   },<br>   &quot;get&quot;: {<br>    &quot;description&quot;: &quot;test&quot;<br>   },<br>   &quot;put&quot;: {<br>    &quot;description&quot;: &quot;test&quot;<br>   }<br>  },<br>  &quot;/users&quot;: {<br>   &quot;get&quot;: {<br>    &quot;description&quot;: &quot;test&quot;<br>   },<br>   &quot;post&quot;: {<br>    &quot;description&quot;: &quot;test&quot;<br>   }<br>  },<br>  &quot;/users/{id}&quot;: {<br>   &quot;delete&quot;: {<br>    &quot;description&quot;: &quot;test&quot;<br>   },<br>   &quot;get&quot;: {<br>    &quot;description&quot;: &quot;test&quot;<br>   },<br>   &quot;put&quot;: {<br>    &quot;description&quot;: &quot;test&quot;<br>   }<br>  }<br> }<br>}</pre><h4>When deployed, it looks like this.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oI3YCAejsYKNsncQ8v35Gw.png" /></figure><p>The results look nicer than expected. Methods and paths were auto extracted from Chi Router nicely. Now all I have left are filling in the parameters within each method so it can show variety of information and be testable, which will be in part 2.</p><p>Thank you for reading part 1 of my efforts on automating Swagger UI from Go-Chi router.</p><p>github address to the project: <a href="https://github.com/printSANO/gorest-boilerplate">https://github.com/printSANO/gorest-boilerplate</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=032698239f2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>