You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
1.4 KiB

package goSyntax
import (
"embed"
"fmt"
"io/fs"
"log"
"net/http"
"os"
)
// 嵌入单文件
// 文本文件
//
//go:embed files/robots.txt
var robots string
// 二进制文件
//
//go:embed files/logo.png
var logo []byte
func EmbedFile() {
fmt.Println(robots)
fmt.Println(logo)
}
// 嵌入目录
//
//go:embed files
var files embed.FS
func EmbedDir() {
// 获取目录下的全部文件
entries, err := files.ReadDir("files")
if err != nil {
log.Fatal(err)
}
// 以此输出每个文件的信息
for _, entry := range entries {
info, _ := entry.Info()
fmt.Println(entry.Name(), entry.IsDir(), info.Size())
}
// 读取文件内容
content, _ := files.ReadFile("files/robots.txt")
fmt.Println(string(content))
}
// 基于embed的http服务器
// 嵌入静态目录
//
//go:embed static
var static embed.FS
// 启动服务器
func StaticEmbedServer() {
// 获取嵌入的static子目录作为文件系统
staticFS, _ := fs.Sub(static, "static")
// 基于static的FS创建 http.FS
// 基于http.FS创建 http.FileServer
// 启动监听 :8080
http.ListenAndServe(":8080", http.FileServer(http.FS(staticFS)))
}
// 非嵌入,运行时读取静态文件的服务器
func StaticRuntimeServer() {
// os.DirFS 基于操作系统的目录文件系统
staticFS := os.DirFS("static")
http.ListenAndServe(":8081", http.FileServer(http.FS(staticFS)))
}