[go] 템플릿 캐시

템플릿 캐싱은 이런 문제를 해결하는 데 도움을 줍니다. 즉, 렌더링된 템플릿을 캐시에 저장하여, 이후에 같은 요청이 있을 때 다시 렌더링하는 데 필요한 비용을 줄입니다. 이를 통해 서버 부하를 줄일 뿐 아니라 사용자 경험을 향상시킬 수 있습니다.

예를 들어, Go 언어에서는 html/template 패키지를 사용하여 템플릿 캐싱을 구현할 수 있습니다. 아래는 간단한 예시입니다.

package main

import (
	"html/template"
	"net/http"
	"sync"
)

var (
	tmplCache  = map[string]*template.Template{}
	tmplCacheMux sync.Mutex
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		tmpl := getTemplate("index.html")
		tmpl.Execute(w, nil)
	})

	http.ListenAndServe(":8080", nil)
}

func getTemplate(name string) *template.Template {
	tmplCacheMux.Lock()
	defer tmplCacheMux.Unlock()

	if tmpl, ok := tmplCache[name]; ok {
		return tmpl
	}

	tmpl := template.Must(template.ParseFiles(name))
	tmplCache[name] = tmpl
	return tmpl
}

이 예제에서 tmplCache는 템플릿을 저장하는 데 사용되는 캐시 맵입니다. getTemplate 함수를 통해 템플릿을 가져오고, 없으면 파싱하여 캐시에 저장합니다.

이러한 방식으로 템플릿 캐싱을 구현하면 웹 애플리케이션의 성능을 향상시키는 데 도움이 될 수 있습니다.