listen and serving http w/ template

This commit is contained in:
Fred 2016-10-01 13:51:35 +02:00
commit 413f8f16d4
2 changed files with 45 additions and 0 deletions

37
main.go Normal file
View File

@ -0,0 +1,37 @@
package main
import (
"html/template"
"log"
"net/http"
"path/filepath"
"sync"
)
// templ represents a single template
type templateHandler struct {
once sync.Once
filename string
templ *template.Template
}
// ServeHTTP handles the HTTP server
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, nil)
}
func NewTemplateHandler() *templateHandler {
return &templateHandler{filename: "chat.html"}
}
func main() {
http.HandleFunc("/", NewTemplateHandler().ServeHTTP)
// start the web server
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}

8
templates/chat.html Normal file
View File

@ -0,0 +1,8 @@
<html>
<head>
<title>Chat</title>
</head>
<body>
Let's chat!
</body>
</html>