所需环境

  • Golang
  • cobar 用于快速开发命令行的包
  • Iris Golang Web 框架
  • go-bindata
  • vue/cli 3.x

创建项目

mkdir $GOPATH/src/project && cd $GOPATH/src/project
go get -u github.com/spf13/cobra/cobra
cobar init

此时目录结构如下:

.
├── LICENSE
├── cmd
│   └── root.go
└── main.go

如果你使用了module,需要执行如下命令:

go mod init

创建命令

cobra add web

执行后将会在cmd目录下创建一个web.go的文件。

创建SPA

npm install -g @vue/cli 或 yarn global add @vue/cli
vue create web
cd web

此时目录机构如下:

.
├── LICENSE
├── cmd
│   ├── root.go
│   └── web.go
├── go.mod
├── go.sum
├── main.go
└── web
    ├── README.md
    ├── babel.config.js
    ├── dist
    ├── node_modules
    ├── package.json
    ├── public
    ├── src
    └── yarn.lock

添加项目依赖

vue add router
vue add vuex
yarn build

当执行yarn build后,将会在web目录下生成dist目录

将静态资源打包成二进制

go get -u github.com/shuLhan/go-bindata/...
go-bindata -pkg web -o web/bindata.go web/dist/...
go build

编辑 web.go

package cmd

import (
	"fmt"
	"github.com/kataras/iris"
	"github.com/kataras/iris/middleware/logger"
	"github.com/kataras/iris/middleware/recover"
	"github.com/spf13/cobra"
	"log"
	"project/web"
)

var (
	host string
	port int
)

// webCmd represents the web command
var webCmd = &cobra.Command{
	Use:   "web",
	Short: "Start a web service",
	Long: `Start a web service`,
	Run: func(cmd *cobra.Command, args []string) {
		server := iris.New()

		server.Use(iris.Gzip)
		server.Use(recover.New())
		server.Use(logger.New())

		// SPA 路由刷新404 处理
		server.OnErrorCode(404, func(ctx iris.Context) {
			ctx.StatusCode(200)
			if err := ctx.View("index.html"); err != nil {
				log.Println(err)
			}
		})

		server.RegisterView(iris.HTML("./web/dist", ".html").Binary(web.Asset, web.AssetNames))

		// 页面路由
		server.Get("/", func(ctx iris.Context) {
			if err := ctx.View("index.html"); err != nil {
				log.Println(err)
			}
		})

		assetHandler := iris.StaticEmbeddedHandler("./web/dist",  web.Asset,  web.AssetNames, false)
		server.SPA(assetHandler).AddIndexName("index.html")

		addr := fmt.Sprintf("%s:%d", host, port)
		if err := server.Run(iris.Addr(addr), iris.WithoutInterruptHandler); err != nil {
			log.Println(err)
		}
	},
}

func init() {
	rootCmd.AddCommand(webCmd)
	webCmd.PersistentFlags().StringVar(&host, "host", "0.0.0.0", "Set listen on IP")
	webCmd.PersistentFlags().IntVar(&port, "port", 7368, "Set listen on port")
}

编译 Go 项目

go build -o spa main.go
./spa web --host localhost --port 8080
Now listening on: http://localhost:8080
Application started. Press CMD+C to shut down.

打开浏览器访问 http://localhost:8080,这样就不用担心在Vue的路由页面刷行会导致404报错了!

效果图

I hope this is helpful, Happy hacking…