Single Page Application基本运用

目录结构

主目录basic

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

示例代码

main.go

  1. package main
  2. import (
  3. "github.com/kataras/iris"
  4. )
  5. //与嵌入式单页面应用程序相同但没有go-bindata,文件是"原始"存储在
  6. //当前系统目录
  7. var page = struct {
  8. Title string
  9. }{"Welcome"}
  10. func newApp() *iris.Application {
  11. app := iris.New()
  12. app.RegisterView(iris.HTML("./public", ".html"))
  13. app.Get("/", func(ctx iris.Context) {
  14. ctx.ViewData("Page", page)
  15. ctx.View("index.html")
  16. })
  17. //或者只是按原样提供index.html:
  18. // app.Get("/{f:path}", func(ctx iris.Context) {
  19. // ctx.ServeFile("index.html", false)
  20. // })
  21. assetHandler := app.StaticHandler("./public", false, false)
  22. //作为SPA的替代方案,您可以查看/routing /dynamic-path/root-wildcard
  23. app.SPA(assetHandler)
  24. return app
  25. }
  26. func main() {
  27. app := newApp()
  28. // http://localhost:8080
  29. // http://localhost:8080/index.html
  30. // http://localhost:8080/app.js
  31. // http://localhost:8080/css/main.css
  32. app.Run(iris.Addr(":8080"))
  33. }

main_test.go

  1. package main
  2. import (
  3. "io/ioutil"
  4. "path/filepath"
  5. "strings"
  6. "testing"
  7. "github.com/kataras/iris/httptest"
  8. )
  9. type resource string
  10. func (r resource) String() string {
  11. return string(r)
  12. }
  13. func (r resource) strip(strip string) string {
  14. s := r.String()
  15. return strings.TrimPrefix(s, strip)
  16. }
  17. func (r resource) loadFromBase(dir string) string {
  18. filename := r.String()
  19. if filename == "/" {
  20. filename = "/index.html"
  21. }
  22. fullpath := filepath.Join(dir, filename)
  23. b, err := ioutil.ReadFile(fullpath)
  24. if err != nil {
  25. panic(fullpath + " failed with error: " + err.Error())
  26. }
  27. result := string(b)
  28. return result
  29. }
  30. var urls = []resource{
  31. "/",
  32. "/index.html",
  33. "/app.js",
  34. "/css/main.css",
  35. }
  36. func TestSPA(t *testing.T) {
  37. app := newApp()
  38. e := httptest.New(t, app, httptest.Debug(false))
  39. for _, u := range urls {
  40. url := u.String()
  41. contents := u.loadFromBase("./public")
  42. contents = strings.Replace(contents, "{{ .Page.Title }}", page.Title, 1)
  43. e.GET(url).Expect().
  44. Status(httptest.StatusOK).
  45. Body().Equal(contents)
  46. }
  47. }

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

  1. body {
  2. background-color: black;
  3. }