fixed templating

This commit is contained in:
David Alasow 2018-12-03 12:29:17 +01:00
parent e077d0484b
commit c5e839e13e
9 changed files with 168 additions and 91 deletions

16
Makefile Normal file
View File

@ -0,0 +1,16 @@
compile: generate clean build
generate:
@printf "Generating code\n"
@go generate ./...
VERSION = $(shell git describe --always --abbrev=40 --dirty)
build:
@printf "Compiling\n"
@mkdir bin/ &> /dev/null || exit 0
@go build
@printf "\n"
clean:
@rm -fr ./bin

View File

@ -0,0 +1,3 @@
package static
//go:generate go-bindata -pkg $GOPACKAGE --prefix "../../static/" ../../static/...

View File

@ -0,0 +1,3 @@
package templates
//go:generate go-bindata -pkg $GOPACKAGE --prefix "../../templates/" ../../templates/...

114
main.go
View File

@ -1,39 +1,16 @@
package main package main
import ( import (
"bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"git.fuyu.moe/Fuyu/router" "git.fuyu.moe/Fuyu/router"
"io/ioutil"
"mime"
"net/http" "net/http"
"path"
"path/filepath"
"strconv" "strconv"
"strings"
"time"
) )
func main() { // nolint: errcheck
//fmt.Println("Hello world")
r := router.New()
r.GET(`/static/*asset`, getStatic)
r.GET(`/`, home)
r.GET(`/compare/:user`, compare)
err := r.Start(`:8070`)
check(err)
}
type jikanAPIUserList struct { type jikanAPIUserList struct {
RequestHash string `json:"request_hash"`
RequestCached bool `json:"request_cached"`
RequestCacheExpiry int `json:"request_cache_expiry"`
Completed int `json:"completed"`
Watching int `json:"watching"`
Dropped int `json:"dropped"`
PlanToWatch int `json:"plan_to_watch"`
OnHold int `json:"on_hold"`
Anime []jikanAPIAnime `json:"anime"` Anime []jikanAPIAnime `json:"anime"`
} }
@ -74,6 +51,16 @@ type meikanAPIIDs struct {
AnidbID int `json:"anidb"` AnidbID int `json:"anidb"`
} }
func main() {
r := router.New()
r.Renderer = NewRenderer()
r.GET(`/static/*asset`, getStatic)
r.GET(`/`, home)
r.GET(`/compare/:user`, compare)
err := r.Start(`:8070`)
check(err)
}
func check(e error) { func check(e error) {
if e != nil { if e != nil {
panic(e) panic(e)
@ -81,31 +68,19 @@ func check(e error) {
} }
func home(c *router.Context) error { func home(c *router.Context) error {
return c.String(200, "Test") return c.Render(200, `index`, ``)
} }
func compare(c *router.Context) error { func compare(c *router.Context) error {
start := time.Now()
user := c.Param(`user`) user := c.Param(`user`)
//https://api.jikan.moe/v3/user/nekomata1037/animelist/all //https://api.jikan.moe/v3/user/nekomata1037/animelist/all
//https://api.meikan.moe/v1/ids/anime //https://api.meikan.moe/v1/ids/anime
jikanList := jikanAPIGetUserAnimelist(user) jikanList := jikanAPIGetUserAnimelist(user)
var anime []meikanListItem var anime []meikanListItem
//fmt.Println(result)
fmt.Println("Getting IDs") fmt.Println("Getting IDs")
IDs := meikanAPIGetIDs() IDs := meikanAPIGetIDs()
confMap := map[int]int{}
for _, v := range IDs {
confMap[v.MyanimelistID] = v.MeikanID
}
fmt.Printf("35248 is %d \n", confMap[35248])
for i := 0; i < len(jikanList.Anime); i++ { for i := 0; i < len(jikanList.Anime); i++ {
//fmt.Println(result.Anime[i].Title) jikanList.Anime[i].MeikanID = IDs[jikanList.Anime[i].MyanimelistID]
for d := 0; d < len(IDs); d++ {
if jikanList.Anime[i].MyanimelistID == IDs[d].MyanimelistID {
jikanList.Anime[i].MeikanID = IDs[d].MeikanID
}
}
temp := meikanListItem{Anime: meikanAnime{ID: jikanList.Anime[i].MeikanID, temp := meikanListItem{Anime: meikanAnime{ID: jikanList.Anime[i].MeikanID,
Title: jikanList.Anime[i].Title, Title: jikanList.Anime[i].Title,
Type: jikanList.Anime[i].Type, Type: jikanList.Anime[i].Type,
@ -114,19 +89,14 @@ func compare(c *router.Context) error {
Rating: jikanList.Anime[i].Score} Rating: jikanList.Anime[i].Score}
switch jikanList.Anime[i].WatchingStatus { switch jikanList.Anime[i].WatchingStatus {
case 1: case 1:
jikanList.Completed++
temp.State = "Watching" temp.State = "Watching"
case 2: case 2:
jikanList.Completed++
temp.State = "Finished" temp.State = "Finished"
case 3: case 3:
jikanList.OnHold++
temp.State = "On Hold" temp.State = "On Hold"
case 4: case 4:
jikanList.Dropped++
temp.State = "Dropped" temp.State = "Dropped"
case 6: case 6:
jikanList.PlanToWatch++
temp.State = "Plan to watch" temp.State = "Plan to watch"
} }
switch jikanList.Anime[i].AiringStatus { switch jikanList.Anime[i].AiringStatus {
@ -135,69 +105,33 @@ func compare(c *router.Context) error {
} }
anime = append(anime, temp) anime = append(anime, temp)
} }
//fmt.Println(anime)
//resJSON, err := json.MarshalIndent(result, "", "\t")
//check(err)
//jsonfile := []byte(resJSON)
elapsed := time.Since(start)
fmt.Printf("Generating json took %s\n", elapsed)
return c.JSON(200, anime) return c.JSON(200, anime)
} }
func jikanAPIGetUserAnimelist(user string) jikanAPIUserList { func jikanAPIGetUserAnimelist(user string) jikanAPIUserList {
var result jikanAPIUserList var userList jikanAPIUserList
start := time.Now()
for i := 1; ; i++ { for i := 1; ; i++ {
resp, err := http.Get("https://api.jikan.moe/v3/user/" + user + "/animelist/all/" + strconv.Itoa(i)) resp, err := http.Get("https://api.jikan.moe/v3/user/" + user + "/animelist/all/" + strconv.Itoa(i))
check(err) check(err)
defer resp.Body.Close()
var tempResult jikanAPIUserList var tempResult jikanAPIUserList
body, err := ioutil.ReadAll(resp.Body) _ = json.NewDecoder(resp.Body).Decode(&tempResult)
check(err) userList.Anime = append(userList.Anime, tempResult.Anime...)
if i == 1 {
_ = json.NewDecoder(bytes.NewReader(body)).Decode(&result)
elapsed := time.Since(start)
fmt.Printf("Searching page 1 took %s\n", elapsed)
continue
} else {
_ = json.NewDecoder(bytes.NewReader(body)).Decode(&tempResult)
result.Anime = append(result.Anime, tempResult.Anime...)
elapsed := time.Since(start)
fmt.Printf("Searching page %d took %s\n", i, elapsed)
}
if len(tempResult.Anime) == 0 { if len(tempResult.Anime) == 0 {
break break
} }
elapsed := time.Since(start)
fmt.Printf("Searching the userlist took %s\n", elapsed)
} }
return result return userList
} }
func meikanAPIGetIDs() []meikanAPIIDs { func meikanAPIGetIDs() map[int]int {
start := time.Now()
resp, err := http.Get("https://api.meikan.moe/v1/ids/anime") resp, err := http.Get("https://api.meikan.moe/v1/ids/anime")
check(err) check(err)
defer resp.Body.Close()
var result []meikanAPIIDs var result []meikanAPIIDs
body, err := ioutil.ReadAll(resp.Body) _ = json.NewDecoder(resp.Body).Decode(&result)
check(err) IDsMap := map[int]int{}
_ = json.NewDecoder(bytes.NewReader(body)).Decode(&result) for _, id := range result {
elapsed := time.Since(start) IDsMap[id.MyanimelistID] = id.MeikanID
fmt.Printf("Getting all the IDs took %s\n", elapsed)
return result
}
func getStatic(c *router.Context) error {
path := path.Clean(strings.TrimPrefix(c.Request.URL.Path, `/static/`))
data, err := ioutil.ReadFile(`./static/` + path)
if err != nil {
return c.String(404, `Resource not found`)
} }
return IDsMap
c.Response.Header().Set(`Content-Type`, mime.TypeByExtension(filepath.Ext(path)))
c.Response.Write(data)
return nil
} }

9
pages/index.html Normal file
View File

@ -0,0 +1,9 @@
<!DOCTYPE html>
<html>
<head>
<title>This is a page</title>
</head>
<body>
</body>
</html>

88
render.go Normal file
View File

@ -0,0 +1,88 @@
package main
import (
"fmt"
"html/template"
"io"
"mime"
"path"
"path/filepath"
"strings"
"git.fuyu.moe/Fuyu/router"
"git.fuyu.moe/Tracreed/mal-importer/internal/static"
"git.fuyu.moe/Tracreed/mal-importer/internal/templates"
)
// Renderer rendders templates
type Renderer struct {
templates map[string]*template.Template
}
// NewRenderer loads all templates
func NewRenderer() *Renderer {
t := &Renderer{}
if t.templates == nil {
t.templates = make(map[string]*template.Template)
}
components := template.New(``)
pages := []string{}
for _, v := range templates.AssetNames() {
if strings.HasPrefix(v, `pages/`) {
pages = append(pages, v)
continue
}
data, err := templates.Asset(v)
if err != nil {
panic(err)
}
template.Must(components.New(v).Parse(string(data)))
}
for _, page := range pages {
data, err := templates.Asset(page)
if err != nil {
panic(err)
}
tmpl, _ := components.Clone()
name := removeExt(strings.TrimPrefix(page, `pages/`))
t.templates[name] = template.Must(tmpl.New(page).Parse(string(data)))
}
return t
}
// Render implements echo's Renderer interface
func (t *Renderer) Render(w io.Writer, name string, data interface{}, c *router.Context) error {
tmpl, ok := t.templates[name]
if !ok {
return fmt.Errorf(`template '%s' not found`, name)
}
templateData := struct {
Content interface{}
}{data}
return tmpl.ExecuteTemplate(w, `base`, templateData)
}
func removeExt(s string) string {
return strings.TrimSuffix(s, path.Ext(s))
}
func getStatic(c *router.Context) error {
path := path.Clean(strings.TrimPrefix(c.Request.URL.Path, `/static/`))
data, err := static.Asset(path)
if err != nil {
return c.String(404, `Resource not found`)
}
c.Response.Header().Set(`Content-Type`, mime.TypeByExtension(filepath.Ext(path)))
_, _ = c.Response.Write(data)
return nil
}

3
static/stylesheet.css Normal file
View File

@ -0,0 +1,3 @@
body {
color: black;
}

View File

@ -0,0 +1,18 @@
{{ define "base" }}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name=viewport content="width=device-width, initial-scale=1">
<title>Meikan data - {{ block "title" . }}Home{{ end }}</title>
<link rel="stylesheet" href="/static/stylesheet.css">
</head>
<body>
<div id="content">
{{ block "body" . }}{{ end }}
</div>
</body>
</html>
{{ end }}

View File

@ -0,0 +1,3 @@
{{ define "body" }}
<h1>Hello, 世界!</h1>
{{ end }}