embed static file
embed static file ์ฌ์ฉ๋ฒ
create file
cat > create-release.json <<EOF
{
"os": "linux",
"arch": "amd64",
"files": [
{
"from": "Readme.md",
"to": "Readme.md"
}
]
}
import
package release
import (
_ "embed" // ์ํฌํธํ์.
)
embed
//go
์์ //
๋ค์์ ์คํ์ด์ค๊ฐ ์์ด์ผ ํ๋ค. create-release.json ์ ํ์ผ์ด๋ฆ
//go:embed create-release.json
var content string
ํ์ผ์ ์ฝ์ด์ string์ ๋ฃ์ด์ค๋ค. ์ด์ ๊ทธ๊ฑธ ๊ทธ๋ฅ ์ฌ์ฉํ๋ฉด๋๋ค.
fmt.Println("File ", content)
build
go build .
run
์์ฑ๋ binary๋ฅผ ๋ค๋ฅธ ํด๋์ ์ฎ๊ธดํ ์คํํด๋ณด๋ฉด ํ๋ฆฐํธ๊ฐ ์๋จ์ ์์ ์๋ค.
multiple file
assets ํด๋๋ฅผ ๋ง๋ค๊ณ ํ์ผ์ ์ถ๊ฐํ์.

hello1.txt
hello1
hello2.txt
hello2

main.go์์ ๋ค์์ฒ๋ผ ์ฝ๋ฉ
package main
import (
"embed"
"net/http"
)
//go:embed assets/*
var assets embed.FS
func main() {
fs := http.FileServer(http.FS(assets))
http.ListenAndServe(":8080", fs)
}
์คํ
go run main.go
curl http://localhost:8080/assets/hello1.txt
curl http://localhost:8080/assets/hello2.txt

์ด๋ ๊ฒ ์ฌ๋ฌํ์ผ์ ๋๊ธธ์๋ ์๋ค.
binary
import _ "embed"
//go:embed logo.png
var logo []byte
์ด์ํ์
์ดํด๊ฐ ๋๋ ์ฝ๋
package main
import (
"embed"
"fmt"
)
//go:embed assets/*
var f embed.FS
func main() {
langs, _ := f.ReadFile("assets/langs.txt")
fmt.Println(string(langs))
words, _ := f.ReadFile("assets/words.txt")
fmt.Println(string(words))
}
์ดํด๊ฐ ์๋๋ ์ฝ๋
//go:embed assets/langs.txt
var f embed.FS
func main() {
langs, _ := f.ReadFile("assets/langs.txt")
fmt.Println(string(langs))
}
๊ณ ๋ ๊ฐ๊ฒฐํจ์ด ์๋ช ์ธ๋ฐ ๊ตฌ์ง ํ์ผ ์ด๋ฆ์ ๋๋ฒ์ฐ๋ค? ์?
ํ์ผ ๋๋ ํ ๋ฆฌ๊ฐ ์๋ ๊ฒฝ์ฐ
์ข ์ด์ํ๋ฐ

assets๊ฐ ์๊ณ testํด๋๊ฐ ์๊ณ testํด๋์์ main ํ์ผ์ด ์๋ค.
//go:embed assets/*
var assets embed.FS
func main() {
fs := http.FileServer(http.FS(assets))
http.ListenAndServe(":8080", fs)
}

๊ฐ์ ์ฝ๋๊ฐ ์๋ฌ๊ฐ ๋๋ค. ์? ์ด๋ป๊ฒ ํ์ง?

์ด๊ฒ๋ ์๋ฌ๊ฐ ๋๋ค. ์ด๋ป๊ฒ ํ์ง?
๋ชจ๋ฅด๊ฒ์...
ํ์ ๊ฒฝ๋ก๋ ์๋๋๋ฐ ์์ ๊ฒฝ๋ก๊ฐ ์๋๋ค...
์ด์๋ ์ด๋ ค์๋๋ฐ ์์ง ์ ํํ ๋ฐฉ๋ฒ์ด ์๋๋ฏ.
Last updated
Was this helpful?