包装路由器

    1. app := iris.New()
    2. app.OnErrorCode(iris.StatusNotFound, func(ctx iris.Context) {
    3. ctx.HTML("<b>Resource Not found</b>")
    4. })
    5. app.Get("/", func(ctx iris.Context) {
    6. ctx.ServeFile("./public/index.html", false)
    7. })
    8. app.Get("/profile/{username}", func(ctx iris.Context) {
    9. ctx.Writef("Hello %s", ctx.Params().Get("username"))
    10. })
    11. //提供来自根“/”的文件,如果我们使用.StaticWeb它可以覆盖
    12. //由于下划线需要通配符,所有路由。
    13. //在这里,我们将看到如何绕过这种行为
    14. //通过创建一个新的文件服务器处理程序和
    15. //为路由器设置包装器(如“低级”中间件)
    16. //为了手动检查我们是否想要正常处理路由器
    17. //或者执行文件服务器处理程序。
    18. //注册路由,它只返回处理程序。
    19. fileServer := app.StaticHandler("./public", false, false)
    20. //使用本机net / http处理程序包装路由器。
    21. //如果url不包含任何“。” (即:.css,.js ......)
    22. //(取决于应用程序,您可能需要添加更多文件服务器异常),
    23. //然后处理程序将执行负责的路由器
    24. //注册路线(看“/”和“/ profile / {username}”)
    25. //如果没有,那么它将根据根“/”路径提供文件。
    26. app.WrapRouter(func(w http.ResponseWriter, r *http.Request, router http.HandlerFunc) {
    27. path := r.URL.Path
    28. //请注意,如果path的后缀为“index.html”,则会自动重定向到“/”,
    29. //所以我们的第一个处理程序将被执行。
    30. if !strings.Contains(path, ".") {
    31. //如果它不是资源,那么就像正常情况一样继续使用路由器. <-- IMPORTANT
    32. router(w, r)
    33. return
    34. }
    35. ctx := app.ContextPool.Acquire(w, r)
    36. fileServer(ctx)
    37. app.ContextPool.Release(ctx)
    38. })
    39. // http://localhost:8080
    40. // http://localhost:8080/index.html
    41. // http://localhost:8080/app.js
    42. // http://localhost:8080/css/main.css
    43. // http://localhost:8080/profile/anyusername
    44. app.Run(iris.Addr(":8080"))
    45. //注意:在这个例子中我们只看到一个用例,
    46. //你可能想要.WrapRouter或.Downgrade以绕过虹膜的默认路由器,即:
    47. //您也可以使用该方法设置自定义代理。
    48. //如果您只想在除root之外的其他路径上提供静态文件
    49. //你可以使用StaticWeb, i.e:
    50. // .StaticWeb("/static", "./public")
    51. // ________________________________requestPath, systemPath