zoukankan      html  css  js  c++  java
  • 几个golang 静态资源嵌入包

    静态资源嵌入二进制文件中,可以方便我们的软件分发(只需要简单的二进制文件就可以了),目前大部分golang 的
    web 应用都是使用类似的方法。
    以下是收集到的一些常见方案

    github.com/go-bindata/go-bindata

    go-bindata 的使用方法是先生成代码,然后使用提供的api引用
    使用流程

    • 生成资源代码
    go-bindata data/
    • 通用引用
    data, err := Asset("pub/style/foo.css")
    if err != nil {
      // Asset was not found.
    }
    // use asset data
    • http server 引用
    go-bindata -fs -prefix "static/" static/
    mux := http.NewServeMux()
    mux.Handle("/static", http.FileServer(AssetFile()))
    http.ListenAndServe(":8080", mux)

    github.com/elazarl/go-bindata-assetfs

    go-bindata-assetfs 是go-bindata的包装,也需要生成代码,但是使用更加简单,便捷
    使用流程

    • 生成代码
    go-bindata-assetfs data/...
    • 资源引用
    http.Handle("/", http.FileServer(assetFS()))

    github.com/rakyll/statik

    也是需要生成代码的

    • 生成代码
    statik -src=/path/to/your/project/public
    • 代码引用
    import (
      "github.com/rakyll/statik/fs"
      _ "./statik" // TODO: Replace with the absolute import path
    )
      // ...
      statikFS, err := fs.New()
      if err != nil {
        log.Fatal(err)
      }
      // Serve the contents over HTTP.
      http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(statikFS)))
      http.ListenAndServe(":8080", nil)

    github.com/gobuffalo/packr

    packr 在使用上就更方便的,导入也很清晰

    • 生成代码
      packr 在开发阶段是不需要生成代码的,我们可以像普通文件的方法使用,当需要嵌入的时候通过工具生成
      就可以自动嵌入了,使用灵活
    package main
    import (
      "fmt"
      "github.com/gobuffalo/packr"
    )
    func main() {
      box := packr.NewBox("./templates")
      s, err := box.FindString("admin/index.html")
      if err != nil {
        log.Fatal(err)
      }
      fmt.Println(s)
    }
    • 构建嵌入
    packr build

    github.com/GeertJohan/go.rice

    go.rice 与packr 的使用类似,开发阶段自己查找,编译构建的时候嵌入

    • 使用
    box := rice.MustFindBox("cssfiles")
    cssFileServer := http.StripPrefix("/css/", http.FileServer(box.HTTPBox()))
    http.Handle("/css/", cssFileServer)
    http.ListenAndServe(":8080", nil)
    • 编译构建
    rice embed-go
    go build

    说明

    以上就是自己目前发现的几个golang比较方便的静态资源嵌入包,后续发现新的再添加完善

    参考资料

    https://github.com/go-bindata/go-bindata 
    https://github.com/elazarl/go-bindata-assetfs 
    https://github.com/rakyll/statik 
    https://github.com/gobuffalo/packr 
    https://github.com/GeertJohan/go.rice

  • 相关阅读:
    停止与暂停线程
    flume日志收集框架
    mysql数据库索引
    junit
    freemarker
    python脚本
    java多线程编程核心技术学习-1
    spring 网站
    [MongoDB]学习笔记--Linux 安装和运行MongoDB
    [Spring MVC]学习笔记--form表单标签的使用
  • 原文地址:https://www.cnblogs.com/rongfengliang/p/11798001.html
Copyright © 2011-2022 走看看