GO · 파일/IO
go:embed 지시문
Go 1.16+의 //go:embed 지시문은 파일이나 디렉터리를 바이너리에 직접 포함합니다. 설정 파일, HTML 템플릿, 정적 자산을 별도 배포 없이 단일 바이너리로 패키징할 수 있습니다.
파일/IO중급embedbinarystatic-assetsgo116
핵심 설명
Go 1.16+의 //go:embed 지시문은 파일이나 디렉터리를 바이너리에 직접 포함합니다. 설정 파일, HTML 템플릿, 정적 자산을 별도 배포 없이 단일 바이너리로 패키징할 수 있습니다.
Go code
package main
import (
"embed"
"fmt"
"io/fs"
"net/http"
"text/template"
)
// 1. 단일 파일 임베딩 (문자열)
//go:embed config.txt
var configStr string
// 2. 단일 파일 임베딩 (바이트 슬라이스)
//go:embed logo.png
var logoBytes []byte
// 3. 디렉터리 임베딩
//go:embed templates/*
var templateFS embed.FS
// 4. 여러 패턴 임베딩
//go:embed static/*.css static/*.js
var staticFS embed.FS
// 실전 예: 템플릿 렌더링
func renderTemplate(name string, data interface{}) (string, error) {
tmplData, err := templateFS.ReadFile("templates/" + name)
if err != nil {
return "", fmt.Errorf("템플릿 읽기 실패: %w", err)
}
tmpl, err := template.New(name).Parse(string(tmplData))
if err != nil {
return "", fmt.Errorf("템플릿 파싱 실패: %w", err)
}
var buf strings.Builder
err = tmpl.Execute(&buf, data)
return buf.String(), err
}
// 실전 예: 정적 파일 서버
func staticFileServer() http.Handler {
// embed.FS에서 서브디렉터리 추출
subFS, _ := fs.Sub(staticFS, "static")
return http.FileServer(http.FS(subFS))
}
func main() {
// 임베딩된 파일 정보
fmt.Println("=== 설정 파일 ===")
fmt.Println(configStr)
fmt.Printf("\n=== 로고 크기: %d bytes ===\n", len(logoBytes))
// 임베딩된 디렉터리 순회
fmt.Println("\n=== 임베딩된 파일 목록 ===")
fs.WalkDir(templateFS, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() {
info, _ := d.Info()
fmt.Printf(" %s (%d bytes)\n", path, info.Size())
}
return nil
})
// HTTP 서버 예제
fmt.Println("\n정적 파일 서버: http://localhost:8080/static/")
// http.Handle("/static/", http.StripPrefix("/static/", staticFileServer()))
// http.ListenAndServe(":8080", nil)
}학습 팁
embed.FS는 io/fs.FS 인터페이스를 구현하므로 http.FS(), template.ParseFS() 등 표준 라이브러리와 바로 연동됩니다.
주의할 점
//go:embed 주석과 변수 선언 사이에 빈 줄이 있으면 작동하지 않습니다. 또한 ..를 포함하는 경로나 숨김 파일(dot file)은 기본적으로 임베딩되지 않습니다.
자주 묻는 질문
go:embed 지시문란 무엇인가요?
Go 1.16+의 //go:embed 지시문은 파일이나 디렉터리를 바이너리에 직접 포함합니다. 설정 파일, HTML 템플릿, 정적 자산을 별도 배포 없이 단일 바이너리로 패키징할 수 있습니다.
go:embed 지시문 학습 시 주의할 점은 무엇인가요?
//go:embed 주석과 변수 선언 사이에 빈 줄이 있으면 작동하지 않습니다. 또한 .. 를 포함하는 경로나 숨김 파일(dot file)은 기본적으로 임베딩되지 않습니다.
Continue Learning
Go 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.