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?