Home  >  Article  >  Backend Development  >  How to package golang

How to package golang

尚
Original
2020-01-13 10:33:285483browse

How to package golang

Golang packaging method:

1. Use go-bindata for packaging:

go-bindata is very simple, The design concept is also not difficult to understand. Its task is to encapsulate static files in a Go language Source Code, and then provide a unified interface. You pass in the file path through this interface, and it will return you the file data of the corresponding path.

To put it simply, it can generate .go files from our static files, so that they can be compiled into binary files. When the project is started, the .go files will be released into static files.

Usage example:

Package the entire static directory and release it when used

# 目录结构
ConfigTest
├── asset
│   └── asset.go 静态文件编译之后的go文件
├── config # 静态文件目录
│   ├── rule.yaml
│   └── rule.json
├── cli # 运行目录
│   ├── config 执行main释放出来的静态文件
│   │   ├── rule.yaml
│   │   └── rule.json
│   └── main # main.go编译之后生成的二进制执行文件
└── main 程序目录
    └── main.go # 源码

Execute the command to package the static files into go files

go-bindata -o=./asset/asset.go -pkg=asset config/...

-o # 指定打包后生成的go文件路径
-pkg # 指定go文件的包名
config/... # 指定需要打包的静态文件路径

2. Use go.rice to package

go.rice also supports packaging static files into go files, but the behavior is very different from go-bindata. From a usage perspective, go.rice is actually a more convenient static file operation library. Packaging static files is an incidental function.

Installation

go get github.com/GeertJohan/go.rice/...

Use

go.rice Treat a directory as a rice.Box operation

import (
    "fmt"
    "html/template"

    "github.com/GeertJohan/go.rice"
)

func main() {
    // 这里写相对于的执行文件的地址
    box, err := rice.FindBox("theme/default")
    if err != nil {
        println(err.Error())
        return
    }
    // 从目录 Box 读取文件
    str, err := box.String("post.html")
    if err != nil {
        println(err.Error())
        return
    }
    t, err := template.New("tpl").Parse(str)
    fmt.Println(t, err)
}

Command

go. The packaging command for rice is rice. It is very straightforward to use: In the go code directory where there is a go.rice operation, directly execute rice embed-go:

rice embed-go
rice -i "github.com/fuxiaohei/xyz" embed-go // -i 处理指定包里的 go.rice 操作

For more golang knowledge, please pay attention to the golang tutorial column on the PHP Chinese website.

The above is the detailed content of How to package golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn