Created
March 9, 2021 15:20
-
-
Save Allenxuxu/a6add7d8730a04a0d2652d5f1103d6a3 to your computer and use it in GitHub Desktop.
go 1.16 embed demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"embed" | |
"fmt" | |
"net/http" | |
"strings" | |
) | |
var ( | |
Version string = strings.TrimSpace(version) | |
//go:embed version.txt | |
version string | |
//go:embed version.txt | |
version2 []byte | |
//go:embed dir dir/home.html | |
//go:embed img/* | |
staticFS embed.FS | |
) | |
func main() { | |
fmt.Printf("Version %q\n", Version) | |
fmt.Printf("Version2 %q\n", string(version2)) | |
// 不支持 局部变量 | |
////go:embed version.txt | |
//var v string | |
//fmt.Printf("v %q\n", v) | |
_, err := staticFS.ReadFile("img/cpu.png") | |
if err !=nil { | |
panic(err) | |
} | |
index, err := staticFS.ReadFile("dir/index.html") | |
if err !=nil { | |
panic(err) | |
} | |
fmt.Printf("dir/index.html %q\n", string(index)) | |
files, err := staticFS.ReadDir("dir") | |
for _, file:=range files { | |
fmt.Printf("file: %s\n", file.Name()) | |
} | |
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticFS)))) | |
if err := http.ListenAndServe(":8080", nil); err !=nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment