initial, broken

This commit is contained in:
2020-03-24 13:32:35 -07:00
parent 471ac01bbd
commit 9ac46046cb
12 changed files with 421 additions and 0 deletions

11
hn/handlers.go Normal file
View File

@@ -0,0 +1,11 @@
package hn
import (
"net/http"
"github.com/labstack/echo"
)
func indexHandler(c echo.Context) error {
return c.Render(http.StatusOK, "index", nil)
}

65
hn/server.go Normal file
View File

@@ -0,0 +1,65 @@
package hn
import (
"os"
"time"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"github.com/labstack/gommon/log"
"github.com/ziflex/lecho/v2"
)
// required for orm
type App struct {
version string
buildarch string
e *echo.Echo
logger *string
db *gorm.DB
startup time.Time
}
func RunServer(version string, buildarch string) int {
a := new(App)
a.version = version
a.buildarch = buildarch
a.startup = time.Now()
a.runForever()
return 0
}
func (a *App) runForever() {
// Echo instance
a.e = echo.New()
lev := log.INFO
if os.Getenv("DEBUG") != "" {
lev = log.DEBUG
}
logger := lecho.New(
os.Stdout,
lecho.WithLevel(lev),
lecho.WithTimestamp(),
lecho.WithCaller(),
)
a.e.Logger = logger
a.e.Use(middleware.RequestID())
// Middleware
a.e.Use(middleware.Logger())
a.e.Use(middleware.Recover())
a.e.Renderer = NewTemplate("./view/")
// Routes
a.e.GET("/", indexHandler)
// Start server
a.e.Logger.Fatal(a.e.Start(":8080"))
}

40
hn/templates.go Normal file
View File

@@ -0,0 +1,40 @@
package hn
import (
"errors"
"html/template"
"io"
"github.com/labstack/echo"
)
// Define the template registry struct
type TemplateRegistry struct {
templates map[string]*template.Template
}
// Implement e.Renderer interface
func (t *TemplateRegistry) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
tmpl, ok := t.templates[name]
if !ok {
err := errors.New("Template not found -> " + name)
return err
}
return tmpl.ExecuteTemplate(w, "base.html", data)
}
func NewTemplate(templatesDir string) *TemplateRegistry {
//ext := ".html"
ins := TemplateRegistry{
templates: map[string]*template.Template{},
}
//layout := templatesDir + "base" + ext
templates := make(map[string]*template.Template)
templates["index"] = template.Must(template.ParseFiles("_pages/index.html", "_layouts/base.html"))
//templates["about.html"] = template.Must(template.ParseFiles("view/about.html", "view/base.html"))
return &ins
}