Skip to content
Permalink
Browse files

トップページをテンプレートで表示

  • Loading branch information...
shibayu36 committed Jun 2, 2019
1 parent 93c2a99 commit ddef40c003464b410ea73cfd6787995c2484136f
Showing with 42 additions and 3 deletions.
  1. +42 −3 web/server.go
@@ -3,8 +3,8 @@ package web
//go:generate go-assets-builder --package=web --output=./templates-gen.go --strip-prefix="/templates/" --variable=Templates ../templates

import (
"fmt"
"html"
"html/template"
"io/ioutil"
"net/http"

"github.com/dimfeld/httptreemux"
@@ -19,6 +19,34 @@ type Server interface {

const sessionKey = "DIARY_SESSION"

var templates map[string]*template.Template

func init() {
var err error
templates, err = loadTemplates()
if err != nil {
panic(err)
}
}

func loadTemplates() (map[string]*template.Template, error) {
templates := make(map[string]*template.Template)
bs, err := ioutil.ReadAll(Templates.Files["main.tmpl"])
if err != nil {
return nil, err
}
mainTmpl := template.Must(template.New("main.tmpl").Parse(string(bs)))
for fileName, file := range Templates.Files {
bs, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
mainTmpl := template.Must(mainTmpl.Clone())
templates[fileName] = template.Must(mainTmpl.New(fileName).Parse(string(bs)))
}
return templates, nil
}

func NewServer(app service.DiaryApp) Server {
return &server{app: app}
}
@@ -43,7 +71,7 @@ func (s *server) Handler() http.Handler {

func (s *server) indexHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
s.renderTemplate(w, r, "index.tmpl", nil)
})
}

@@ -54,3 +82,14 @@ var csrfMiddleware = func(next http.Handler) http.Handler {
var csrfToken = func(r *http.Request) string {
return nosurf.Token(r)
}

func (s *server) renderTemplate(w http.ResponseWriter, r *http.Request, tmpl string, data map[string]interface{}) {
if data == nil {
data = make(map[string]interface{})
}
data["CSRFToken"] = csrfToken(r)
err := templates[tmpl].ExecuteTemplate(w, "main.tmpl", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}

0 comments on commit ddef40c

Please sign in to comment.
You can’t perform that action at this time.