将静态资源打包进二进制文件有好多方便的地方
- 方便客户演示
- 代码简单加密
- 运行方便
statik 就是一款在golang 中用的比较多,nodejs 有一款pkg (oclif 就推荐使用此工具)
statik 安装
go get github.com/rakyll/statik
使用
statik -src= resourceurl
项目使用
- 简单项目
cd $GOPATH/src/github.com/rongfengliang/webui
dep init
- 项目目录
- 配置
//go:generate statik -src=./ui
package main
import (
"log"
"net/http"
"github.com/rakyll/statik/fs"
_ "github.com/rongfengliang/webui/statik"
)
func main() {
statikFS, err := fs.New()
if err != nil {
log.Fatal(err)
}
http.Handle("/", http.StripPrefix("/ui", http.FileServer(statikFS)))
http.ListenAndServe(":10080", nil)
}
静态资源目录结构
docker 集成
Dockerfile :
# build stage
FROM golang:1.10-alpine AS build-env
RUN apk --no-cache add build-base git bzr mercurial gcc && \
go get github.com/rakyll/statik
ENV D=/go/src/github.com/rongfengliang/webui
ADD . $D
RUN cd $D && go generate && go build -o webui . && cp webui /tmp/
FROM alpine:latest
WORKDIR /app
COPY --from=build-env /tmp/webui /app/webui
CMD ["./webui"]
docker-compose.yaml:
version: "3"
services:
ui:
image: dalongrong/webui
build: ./
ports:
- "8080:10080"
参考资料
https://github.com/rongfengliang/statik-web-demo
https://github.com/rakyll/statik