Add boilerplate

This commit is contained in:
Crow Crowcrow 2017-10-09 01:33:20 +02:00
parent a5fdd8a103
commit f9ed3ac363
6 changed files with 145 additions and 0 deletions

21
server/main.go Normal file
View file

@ -0,0 +1,21 @@
package main
import "github.com/labstack/echo"
func main() {
e := echo.New()
t := Template{}
t.Reset()
e.Renderer = &t
e.Static("/static", "static/")
e.GET("/", index)
e.Logger.Fatal(e.Start(":8080"))
}
func index(c echo.Context) error {
return c.Render(200, "index", nil)
}

66
server/templates.go Normal file
View file

@ -0,0 +1,66 @@
package main
import (
"fmt"
"html/template"
"io"
"log"
"os"
"path"
"path/filepath"
"strings"
"github.com/labstack/echo"
)
// Reset reads all the templates
func (t *Template) Reset() {
pagesPath := `templates/pages/`
componentsPath := `templates/components/*.gohtml`
if t.templates == nil {
t.templates = make(map[string]*template.Template)
}
pages := []string{}
err := filepath.Walk(pagesPath, func(path string, f os.FileInfo, err error) error {
if err != nil {
return err
}
if !f.IsDir() {
pages = append(pages, path)
}
return nil
})
if err != nil {
log.Fatal(err)
}
components, err := filepath.Glob(componentsPath)
if err != nil {
log.Fatal(err)
}
for _, layout := range pages {
files := append(components, layout)
name := path.Base(removeExt(layout))
t.templates[name] = template.Must(template.New(``).ParseFiles(files...))
}
}
// Render echo Render func
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
tmpl, ok := t.templates[name]
if !ok {
return fmt.Errorf("template '%s' not found", name)
}
return tmpl.ExecuteTemplate(w, "base", data)
}
func removeExt(s string) string {
return strings.TrimSuffix(s, path.Ext(s))
}

10
server/types.go Normal file
View file

@ -0,0 +1,10 @@
package main
import (
"html/template"
)
// Template echo template struct
type Template struct {
templates map[string]*template.Template
}