packrstatik

项目结构

  • golang mod
go mod init github.com/rongfengliang/rice-app
  • 项目结构
├── Makefile
├── README.md
├── go.mod
├── go.sum
├── http-files
│ ├── app.css
│ └── index.html
├── main.go
└── rice-box.go
  • 代码说明
    http-files 为静态资源的位置,我们可以通过代码直接引用,main.go 为入口,Makefile 为通过make 的跨平台编译处理
    rice-box.go 是使用go generate 生成的资源代码
    main.go
package main
//go:generate go run github.com/GeertJohan/go.rice/rice embed-go
import (
  "log"
  "net/http"
  rice "github.com/GeertJohan/go.rice"
)
func main() {
  http.Handle("/", http.FileServer(rice.MustFindBox("http-files").HTTPBox()))
  err := http.ListenAndServe(":8080", nil)
  if err != nil {
    log.Fatalln("some wrong will exit")
  }
}​

go.mod

module github.com/rongfengliang/rice-app
go 1.13
require github.com/GeertJohan/go.rice v1.0.0
 

Makefile

build-app: clean make-dir generate build-mac build-linux build-windows
clean:
  rm -rf build/* && rm -rf rice-box.go
generate:
  go generate
make-dir:
  mkdir -p build/{mac,linux,windows}
build-mac:
  CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -o build/mac 
build-linux:
  CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/linux 
build-windows:
  CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -o build/windows

运行&&效果

  • 运行&&构建
make
  • 运行效果
./build/mac/rice-app 

效果

说明

go.rice 在功能上与packr很类似,都是一个很不错的golang 静态资源嵌入工具包

参考资料