单页面应用(embedded Single Page Application Other router)

目录结构

主目录embeddedSPAWithOtherRoutes

  1. —— main.go
  2. —— public
  3. —— css
  4. —— main.css
  5. —— index.html
  6. —— app.js

示例代码

main.go

  1. package main
  2. import "github.com/kataras/iris"
  3. // $ go get -u github.com/shuLhan/go-bindata/...
  4. // $ go-bindata ./public/...
  5. // $ go build
  6. // $ ./embedded-single-page-application-with-other-routes
  7. func newApp() *iris.Application {
  8. app := iris.New()
  9. app.OnErrorCode(404, func(ctx iris.Context) {
  10. ctx.Writef("404 not found here")
  11. })
  12. app.StaticEmbedded("/", "./public", Asset, AssetNames)
  13. //注意:
  14. //如果您想要一个动态索引页面,请查看file-server/embedded-single-page-application
  15. //正在注册基于bindata的视图引擎和根路由。
  16. app.Get("/ping", func(ctx iris.Context) {
  17. ctx.WriteString("pong")
  18. })
  19. app.Get("/.well-known", func(ctx iris.Context) {
  20. ctx.WriteString("well-known")
  21. })
  22. app.Get(".well-known/ready", func(ctx iris.Context) {
  23. ctx.WriteString("ready")
  24. })
  25. app.Get(".well-known/live", func(ctx iris.Context) {
  26. ctx.WriteString("live")
  27. })
  28. app.Get(".well-known/metrics", func(ctx iris.Context) {
  29. ctx.Writef("metrics")
  30. })
  31. return app
  32. }
  33. func main() {
  34. app := newApp()
  35. // http://localhost:8080/index.html
  36. // http://localhost:8080/app.js
  37. // http://localhost:8080/css/main.css
  38. // http://localhost:8080/ping
  39. // http://localhost:8080/.well-known
  40. // http://localhost:8080/.well-known/ready
  41. // http://localhost:8080/.well-known/live
  42. // http://localhost:8080/.well-known/metrics
  43. //记住:我们可以使用根通配符`app.Get("/{param:path}")`并手动提供文件。
  44. app.Run(iris.Addr(":8080"))
  45. }

/public/app.js

  1. window.alert("app.js loaded from \"/");

/public/index.html

  1. <html>
  2. <head>
  3. <title>{{ .Page.Title }}</title>
  4. </head>
  5. <body>
  6. <h1> Hello from index.html </h1>
  7. <script src="/app.js"> </script>
  8. </body>
  9. </html>

/public/css/main.css

body {
    background-color: black;
}