Go language - package static files

Keywords: JSON Go github encoding

For the developers of Go language, while enjoying the convenience of the language, we are also keen on the final compilation of a single executable.

However, Go did not compile our static resource file when compiling into binary file. If we are developing web application, we need to find a way to compile our static file.

This article has collected some methods used in Go language to package static files into compiled files during compilation.

go-bindata

You can see a lot of static packaging libraries in Awesome of go language, but you can't see go bindata. Go bindata is obviously more popular.

Go bindata is very simple, and the design concept is not difficult to understand. Its task is to encapsulate the static files in a go language Source Code, and then provide a unified interface through which you pass in the file path, and it will return the file data of the corresponding path to you. That is to say, it doesn't care whether your file is character type or byte type. You can handle it by yourself, and it only deals with packaging.

In short, it can generate our static files into. go files, which can be compiled into binary files, and then released into static files when the project starts

download

go get -u github.com/jteeuwen/go-bindata/...

Installation confirmation

C:\Users\Administrator\Desktop>go-bindata -version
go-bindata 3.1.0 (Go runtime go1.14).
Copyright (c) 2010-2013, Jim Teeuwen.

Note: GOPATH must be under environment variable

Use

directory structure

ConfigTest
├── asset
│   └── asset.go     After static file compilationgofile
├── cli              # Running directory
├── config           # Profile directory
│   ├── config.json 
│   └── config.yaml
└── main            # Program directory
    └── main.go     # Source code

config.yaml content

enabled: true
path: aaaaa
id: 10

config.json content

{
    "enabled": true,
    "path": "xxxx",
    "id": 111
}

Execute the command to package the static file into a go file

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

-o output file to. / asset/asset.go
Package name - pkg=asset
config/… #Specify the static file path to package Include all subdirectories

//Please refer to: https://www.cnblogs.com/landv/p/11577213.html

The path becomes:

ConfigTest
├── asset
│   └── asset.go     After static file compilationgofile
├── cli              # Running directory
├── config           # Profile directory
│   ├── config.json 
│   └── config.yaml
└── main            # Program directory
    └── main.go     # Source code

Example 1

  • main.go
package main

import (
	"configTest/asset"
	"encoding/json"
	"fmt"
	"gopkg.in/yaml.v2"
	"log"
	"os"
	"path/filepath"
)

type conf struct {
	Enabled bool
	Path    string
	ID      int
}

func (c *conf) ReadYaml() {
	data, _ := asset.Asset("config/config.yaml")
	err := yaml.Unmarshal(data, &c)
	if err != nil {
		log.Fatalf("Unmarshal: %v", err)
	}
}

func (c *conf) ReadJson() {
	data, _ := asset.Asset("config/config.json")
	err := json.Unmarshal(data, &c)
	if err != nil {
		log.Fatalf("Unmarshal: %v", err)
	}
}

// Extract dir to the current directory: extract the generated. go file as the current file
func restore() {
  // Please refer to: https://www.cnblogs.com/landv/p/11577213.html
	dirs := []string{"config"} // Set directory to release
	isSuccess := true
	for _, dir := range dirs {
		// Extract the dir directory to the current directory
		if err := asset.RestoreAssets("./", dir); err != nil {
			isSuccess = false
			break
		}
	}
	if !isSuccess {
		for _, dir := range dirs {
			os.RemoveAll(filepath.Join("./", dir))
		}
	}
}

func main() {
	var c, j conf
	j.ReadJson()
	fmt.Println("json:", j)
	c.ReadYaml()
	fmt.Println("yaml:", c)
	fmt.Println("Release static files")
	restore()
}
  • Compiling the main.go execution binary
cd cli && go build ../main/main.go
./main

json: {true xxxx 111}
yaml: {true aaaaa 10}
Release static files

After execution, the config directory and the following static files will be extracted automatically

ConfigTest
├── asset
│   └── asset.go     After static file compilationgofile
├── cli              # Running directory
│   ├── config       # Calledrestore()This file will be generated
│   │   ├── config.json
│   │   └── config.yaml
│   └── main        # main.goBinary executor generated after compilation
├── config          # Profile directory
│   ├── config.json 
│   └── config.yaml
└── main            # Program directory
    └── main.go     # Source code

Example 2: http.FileSystem

http.FileSystem is the interface defining HTTP static file service. The third-party package of go bindata, go bindata assetfs, implements this interface and supports HTTP's access to static file directories.

main.go

package main

import (
	"configTest/asset"
	assetfs "github.com/elazarl/go-bindata-assetfs"
	"net/http"
)

func myhttp() {
	fs := assetfs.AssetFS{
		Asset:     asset.Asset,
		AssetDir:  asset.AssetDir,
		AssetInfo: asset.AssetInfo,
	}
	http.Handle("/", http.FileServer(&fs))
	http.ListenAndServe(":12345", nil)
}

func main() {
	myhttp()
}

Visit http://localhost:12345 to see the contents of the embedded static resource directory

, same as Nginx viewing static file directory.

257 original articles published, 72 praised, 220000 visitors+
His message board follow

Posted by burfo on Thu, 12 Mar 2020 02:21:59 -0700