# embed static file

## embed static file 사용법

### create file

```sh
cat > create-release.json <<EOF
{
  "os": "linux",
  "arch": "amd64",
  "files": [
    {
      "from": "Readme.md",
      "to": "Readme.md"
    }
  ]
}
```

### import

```go
package release

import (
  _ "embed" // 임포트하자.
)
```

### embed

`//go` 에서 `//` 다음에 스페이스가 없어야 한다. create-release.json 은 파일이름

```go
//go:embed create-release.json
var content string
```

파일을 읽어서 string에 넣어준다. 이제 그걸 그냥 사용하면된다.

```go
fmt.Println("File ", content)
```

### build

```sh
go build .
```

### run

생성된 binary를 다른 폴더에 옮긴후 실행해보면 프린트가 잘됨을 알수 있다.

## multiple file

assets 폴더를 만들고 파일을 추가하자.

![](/files/i3w0AVIO4UnV48CIryND)

hello1.txt

```sh
hello1
```

hello2.txt

```sh
hello2
```

![](/files/SCpn7pV3klZwgl12ngYY)

main.go에서 다음처럼 코딩

```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)
}
```

### 실행

```sh
go run main.go

curl http://localhost:8080/assets/hello1.txt
curl http://localhost:8080/assets/hello2.txt
```

![](/files/9aOegh8k5PfYTUYvvSdV)

이렇게 여러파일을 넘길수도 있다.

## binary

```go
import _ "embed"

//go:embed logo.png
var logo []byte
```

## 이상한점

이해가 되는 코드

```go
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
//go:embed assets/langs.txt
var f embed.FS

func main() {

    langs, _ := f.ReadFile("assets/langs.txt")
    fmt.Println(string(langs))

}
```

고는 간결함이 생명인데 구지 파일 이름을 두번쓰네? 왜?

## 파일 디렉토리가 있는 경우

좀 이상한데

![](/files/rVG6Yh4Kv8EI3TUC1QkN)

assets가 있고 test폴더가 잇고 test폴더안에 main 파일이 있다.

```go
//go:embed assets/*
var assets embed.FS

func main() {
  fs := http.FileServer(http.FS(assets))
  http.ListenAndServe(":8080", fs)
}
```

![](/files/eKodi8gUZFit03VLxnyA)

같은 코드가 에러가 난다. 왜? 어떻게 하지?

![](/files/UftYplSFFxQGeJ5Zg0fm)

이것도 에러가 난다. 어떻게 하지?

모르겟음...

하위 경로는 잘되는데 상위 경로가 안된다...

이슈는 열려잇는데 아직 정확한 방법이 없는듯.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://teamsmiley.gitbook.io/devops/go-lang/embed-file.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
