1
0
mirror of https://github.com/muety/wakapi.git synced 2023-08-10 21:12:56 +03:00
wakapi/routes/routes.go

114 lines
2.3 KiB
Go
Raw Normal View History

package routes
import (
"fmt"
"github.com/markbates/pkger"
"github.com/muety/wakapi/config"
"github.com/muety/wakapi/models"
"github.com/muety/wakapi/utils"
"html/template"
"io/ioutil"
2021-02-03 22:53:27 +03:00
"net/http"
"path"
2020-05-24 17:34:32 +03:00
"strings"
)
2020-11-08 14:46:12 +03:00
func Init() {
loadTemplates()
}
2021-02-03 22:53:27 +03:00
type action func(w http.ResponseWriter, r *http.Request) (int, string, string)
var templates map[string]*template.Template
func loadTemplates() {
2021-01-24 02:13:37 +03:00
const tplPath = "/views"
tpls := template.New("").Funcs(template.FuncMap{
"json": utils.Json,
"date": utils.FormatDateHuman,
"simpledate": utils.FormatDate,
"simpledatetime": utils.FormatDateTime,
"title": strings.Title,
"join": strings.Join,
"add": utils.Add,
"capitalize": utils.Capitalize,
"toRunes": utils.ToRunes,
"entityTypes": models.SummaryTypes,
"typeName": typeName,
"isDev": func() bool {
return config.Get().IsDev()
},
"getBasePath": func() string {
return config.Get().Server.BasePath
},
2020-05-24 22:42:15 +03:00
"getVersion": func() string {
return config.Get().Version
2020-05-24 22:42:15 +03:00
},
2020-10-16 17:58:16 +03:00
"getDbType": func() string {
return strings.ToLower(config.Get().Db.Type)
2020-10-16 17:58:16 +03:00
},
"htmlSafe": func(html string) template.HTML {
return template.HTML(html)
},
})
templates = make(map[string]*template.Template)
dir, err := pkger.Open(tplPath)
if err != nil {
panic(err)
}
2021-01-24 02:13:37 +03:00
defer dir.Close()
files, err := dir.Readdir(0)
if err != nil {
panic(err)
}
for _, file := range files {
tplName := file.Name()
if file.IsDir() || path.Ext(tplName) != ".html" {
continue
}
templateFile, err := pkger.Open(fmt.Sprintf("%s/%s", tplPath, tplName))
if err != nil {
panic(err)
}
templateData, err := ioutil.ReadAll(templateFile)
if err != nil {
panic(err)
}
templateFile.Close()
tpl, err := tpls.New(tplName).Parse(string(templateData))
if err != nil {
panic(err)
}
templates[tplName] = tpl
}
}
func typeName(t uint8) string {
if t == models.SummaryProject {
return "project"
}
if t == models.SummaryLanguage {
return "language"
}
if t == models.SummaryEditor {
return "editor"
}
if t == models.SummaryOS {
return "operating system"
}
if t == models.SummaryMachine {
return "machine"
}
return "unknown"
}
func defaultErrorRedirectTarget() string {
return fmt.Sprintf("%s/?error=unauthorized", config.Get().Server.BasePath)
}