Basic Usage Examples

First create a static folder under the project (name it whatever you want, no rules), then create several files under the project, and fill each file with the same directory structure as the I am S1 / S2 / S3 file

Import the string

package main

import(_"embed"
	"fmt"
)

//go:embed static/s1.txt
var content string
func main(a) {
	fmt.Printf(Static file contents: %s\n,content)
}
Copy the code

Output:

Static file contents: I am in s1 fileCopy the code

Import as byte []

package main

import(_"embed"
	"fmt"
)

//go:embed static/s1.txt
var content []byte
func main(a) {
	fmt.Printf(Static file contents: %s\n.string(content))
}
Copy the code

Output:

Static file contents: I am in s1 fileCopy the code

Import as FS file system

The Open method

package main

import (
	"embed"
	"fmt"
)

//go:embed static
var content embed.FS
func main(a) {
	// Open the static/s1. TXT file in FS
	file,err:=content.Open("static/s1.txt")
	defer file.Close()
	iferr ! =nil {
		fmt.Println(err)
	}

    // Read data from File
	var c = make([]byte.30)
	l,err:=file.Read(c)

	fmt.Printf("Contents of Open: %s\n",c)
	fmt.Printf("Open read length: %d\n",l)
}
Copy the code

Output:

I am Open in s1Copy the code

ReadDir method

package main

import (
	"embed"
	"fmt"
)

//go:embed static
var content embed.FS
func main(a) {
	// Open the file
	files,err:=content.ReadDir("static")
	iferr ! =nil {
		fmt.Println(err)
	}
	for _,f:=range files{
		fmt.Printf("File name: %s\n",f.Name())
		fmt.Print("Is it a folder?")
		fmt.Println(f.IsDir())
		fileInfo,_:=f.Info()
		fmt.Printf("File permission: %s\n",fileInfo.Mode())
		fmt.Println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --")}}Copy the code

Output:

File name: s1. TXT whether folder: false file permissions: - r -- r -- r -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- name: s2. TXT whether folder: false file permissions: - r -- r -- r -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- name: s3. TXT whether folder: false file permissions: -r--r--r-- --------------------------------------Copy the code

ReadFile method

package main

import (
	"embed"
	"fmt"
)

//go:embed static
var content embed.FS
func main(a) {
	c2,_:=content.ReadFile("static/s1.txt")
	fmt.Printf("ReadFile contents: %s\n",c2)
}
Copy the code

Output:

ReadFile contents: I am in s1Copy the code