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?