Go 1.16 launches embedded files

Time:2021-10-31

Original text from:Go 1.16 launches embedded files

Go languageOfficial maintenance team RScGitHub IssueIt is proposed to directly support embedded files in go command line. Unexpectedly, it will be implemented directly in a few months, and it is expected to be launched in 2021go 1.16Version direct supportEmbedded Kit。 With this function, you can directly package static files or project settings, which makes deployment easier. Let’s see how the authorities use it.

embed package

Look directly at the official examples:

package main

import "embed"

func main() {
    //go:embed hello.txt
    var s string
    print(s)

    //go:embed hello.txt
    var b []byte
    print(string(b))

    //go:embed hello.txt
    var f embed.FS
    data, _ := f.ReadFile("hello.txt")
    print(string(data))

}

You can see Keywords:go:embed, static files can be directly used for development through annotations. In addition, multiple files or directories can be referenced:

package server

import "embed"

// content holds our static web server content.
//go:embed image/* template/*
//go:embed html/index.html
var content embed.FS

Can seego:embedSupport multiple directories, single file or multiple files, if not usedembed.FS, please add when importing_, examples are as follows:

package main

import _ "embed"

func main() {
    //go:embed hello.txt
    var s string
    print(s)

    //go:embed hello.txt
    var b []byte
    print(string(b))
}

With this package, you don’t need it anymoreThird party suite resource embeddingNow, let’s see how to integrate the embedded suite intoGin

Integrate gin framework

Let’s assume that gin needs to contain static pictures and templates. The following is the directory structure:

├── assets
│   ├── favicon.ico
│   └── images
│       └── example.png
├── go.mod
├── go.sum
├── main.go
└── templates
    ├── foo
    │   └── bar.tmpl
    └── index.tmpl

How to package template and assets directories directly into go? Look directlymain.go

package main

import (
    "embed"
    "html/template"
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    //go:embed assets/* templates/*
    var f embed.FS

    router := gin.Default()
    templ := template.Must(template.New("").ParseFS(f, "templates/*.tmpl", "templates/foo/*.tmpl"))
    router.SetHTMLTemplate(templ)

    // example: /public/assets/images/example.png
    router.StaticFS("/public", http.FS(f))

    router.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl", gin.H{
            "title": "Main website",
        })
    })

    router.GET("/foo", func(c *gin.Context) {
        c.HTML(http.StatusOK, "bar.tmpl", gin.H{
            "title": "Foo website",
        })
    })

    router.GET("favicon.ico", func(c *gin.Context) {
        file, _ := f.ReadFile("assets/favicon.ico")
        c.Data(
            http.StatusOK,
            "image/x-icon",
            file,
        )
    })

    router.Run(":8080")
}

Developers can simply wrap static files in two lines:

//go:embed assets/* templates/*
var f embed.FS

The route of static files can be set directly through the following:

// example: /public/assets/images/example.png
router.StaticFS("/public", http.FS(f))

Or throughReadFileRead single file:

router.GET("favicon.ico", func(c *gin.Context) {
    file, _ := f.ReadFile("assets/favicon.ico")
    c.Data(
        http.StatusOK,
        "image/x-icon",
        file,
    )
})

Program examples can be found directly inFind it here

Experience

The go team is really attentive and will incorporate some common core functions into the official maintenance to maintain subsequent updates. With this function, in the go deployment process, you can directly skip the static file and join the docker. Some confidential files of future projects can also be directly replaced in the CI process through this method, and then go build.

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Recommended Today

01. MySQL architecture and SQL execution process

MySQL notes are divided into four parts:1. MySQL architecture and SQL execution process 2. MySQL index principle and usage principle 3. MySQL transaction and lock details 4. MySQL performance optimization summaryObjectives of this section: 1. Understand the execution process of MySQL statements 2. Understand the architecture and internal modules of MySQL 3. Master the disk […]