go react web服务器

照着官方文档 完成 3子棋

react 官方指南

构件react

npm run build

程序被构件到了 build 目录下

新建 main.go,利用go-bindata 把 react相关文件打包到一个go文件中

//go:generate go-bindata -prefix build -pkg static -o internal/static/static_gen.go build/...
package main
go generate

这样 build 目录下的所有文件 都被打包到了  internal/static/static_gen.go 文件

go-bindata用法可参考: go-bindata 和 sql-migrate 用法

完成 main.go

//go:generate go-bindata -prefix build -pkg static -o internal/static/static_gen.go build/...
package main

import (
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"./internal/static"
	"github.com/gorilla/mux"
	log "github.com/sirupsen/logrus"
	assetfs "github.com/elazarl/go-bindata-assetfs"
)

func getHTTPHandler() (http.Handler) {
	r := mux.NewRouter()

	// setup static file server
	r.PathPrefix("/").Handler(http.FileServer(&assetfs.AssetFS{
		Asset:     static.Asset,
		AssetDir:  static.AssetDir,
		AssetInfo: static.AssetInfo,
		Prefix:    "",
	}))

	return r
}

func startServer() {
	httpHandler := getHTTPHandler()
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {	
		httpHandler.ServeHTTP(w, r)
	})

	go func() {
		http.ListenAndServe(":3333", handler)
	}()
}

func wait() {
	sigChan := make(chan os.Signal)
	exitChan := make(chan struct{})
	signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
	log.WithField("signal", <-sigChan).Info("signal received")
	go func() {
		log.Warning("stopping ...")
		// todo: handle graceful shutdown?
		exitChan <- struct{}{}
	}()
	select {
	case <-exitChan:
	case s := <-sigChan:
		log.WithField("signal", s).Info("signal received, stopping immediately")
	}
}

func main() {
	startServer()
	wait()
}

代码其实蛮简单的

go 创建 http 文件服务器

go run main.go

然后浏览器上 http://localhost:3333/  访问即可

猜你喜欢

转载自blog.csdn.net/wangjunsheng/article/details/81071813