EPguy
[Golang] text/template 패키지로 정적인 페이지 띄우기 본문
1. 코드
main.go
package main
import (
"flag"
"log"
"net/http"
"path/filepath"
"sync"
"text/template"
)
type templateHandler struct {
once sync.Once
filename string
templ *template.Template
}
func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
t.once.Do(func() {
t.templ = template.Must(template.ParseFiles(filepath.Join("templates", t.filename)))
})
t.templ.Execute(w, r)
}
func main() {
var port = flag.String("port", ":8080", "서버 포트에 대한 옵션입니다. EX) :8080")
flag.Parse()
http.Handle("/", &templateHandler{filename: "chat.html"})
log.Println("서버 시작 중 입니다. 사용중인 포트 : ", *port)
if err := http.ListenAndServe(*port, nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}
templates/chat.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>hi</div>
</body>
</html>
2. 실행
go run . -addr=:8080
'개발 > Golang' 카테고리의 다른 글
[Golang] flag 패키지로 command-line flags 받기 (0) | 2023.11.29 |
---|