github.com/hellobchain/third_party@v0.0.0-20230331131523-deb0478a2e52/go-chi/chi/middleware/url_format.go (about) 1 package middleware 2 3 import ( 4 "context" 5 "strings" 6 7 "github.com/hellobchain/newcryptosm/http" 8 9 "github.com/hellobchain/third_party/go-chi/chi" 10 ) 11 12 var ( 13 // URLFormatCtxKey is the context.Context key to store the URL format data 14 // for a request. 15 URLFormatCtxKey = &contextKey{"URLFormat"} 16 ) 17 18 // URLFormat is a middleware that parses the url extension from a request path and stores it 19 // on the context as a string under the key `middleware.URLFormatCtxKey`. The middleware will 20 // trim the suffix from the routing path and continue routing. 21 // 22 // Routers should not include a url parameter for the suffix when using this middleware. 23 // 24 // Sample usage.. for url paths: `/articles/1`, `/articles/1.json` and `/articles/1.xml` 25 // 26 // func routes() http.Handler { 27 // r := chi.NewRouter() 28 // r.Use(middleware.URLFormat) 29 // 30 // r.Get("/articles/{id}", ListArticles) 31 // 32 // return r 33 // } 34 // 35 // func ListArticles(w http.ResponseWriter, r *http.Request) { 36 // urlFormat, _ := r.Context().Value(middleware.URLFormatCtxKey).(string) 37 // 38 // switch urlFormat { 39 // case "json": 40 // render.JSON(w, r, articles) 41 // case "xml:" 42 // render.XML(w, r, articles) 43 // default: 44 // render.JSON(w, r, articles) 45 // } 46 // } 47 // 48 func URLFormat(next http.Handler) http.Handler { 49 fn := func(w http.ResponseWriter, r *http.Request) { 50 ctx := r.Context() 51 52 var format string 53 path := r.URL.Path 54 55 if strings.Index(path, ".") > 0 { 56 base := strings.LastIndex(path, "/") 57 idx := strings.Index(path[base:], ".") 58 59 if idx > 0 { 60 idx += base 61 format = path[idx+1:] 62 63 rctx := chi.RouteContext(r.Context()) 64 rctx.RoutePath = path[:idx] 65 } 66 } 67 68 r = r.WithContext(context.WithValue(ctx, URLFormatCtxKey, format)) 69 70 next.ServeHTTP(w, r) 71 } 72 return http.HandlerFunc(fn) 73 }