handlers/book.go
このサイトを動かすコードです。どのファイルから読めばよいかは第14章の読み順で確認できます。
package handlers
import (
"html/template"
"io/fs"
"net/http"
"go.laravel.com/auth"
"go.laravel.com/db"
"go.laravel.com/web"
"laravel-go-kaitai/content"
"laravel-go-kaitai/models"
)
type page struct {
Title, Current string
Parts []content.Part
Chapter, Previous, Next content.Chapter
Outline []content.Heading
Body template.HTML
SourcePath, SourceCode string
Lab labPage
Account any
Progress studyProgress
ChapterCompleted bool
}
func Home(*web.Request) *web.Response {
return web.View("home", page{Current: "home", Parts: content.Parts})
}
func Index(*web.Request) *web.Response {
return web.View("index", page{Title: "全章の目次", Current: "index", Parts: content.Parts})
}
func Chapter(r *web.Request) *web.Response {
chapter, previous, next := content.Lookup(r.PathValue("slug"))
if chapter.Slug == "" {
return NotFound(r)
}
body, outline, err := content.Read(chapter.Number)
if err != nil {
return web.Fail(err)
}
var completed bool
if viewer := auth.User[models.User](r); viewer != nil && !viewer.MustChangePassword {
completed, err = db.Table("chapter_progress").WhereEq("user_id", viewer.ID).
WhereEq("chapter_slug", chapter.Slug).Exists(r)
if err != nil {
return web.Fail(err)
}
}
return web.View("chapter", page{
Title: chapter.Title, Current: "index", Parts: content.Parts,
Chapter: chapter, Previous: previous, Next: next,
Outline: outline, Body: body, ChapterCompleted: completed,
})
}
func Glossary(*web.Request) *web.Response {
body, _, err := content.Read("glossary")
if err != nil {
return web.Fail(err)
}
return web.View("glossary", page{Title: "用語集", Current: "glossary", Body: body})
}
var sourcePaths = map[string]string{
"main": "main.go",
"bootstrap": "bootstrap/app.go",
"routes": "routes/web.go",
"handlers": "handlers/book.go",
"catalog": "content/book.go",
"chapter-view": "resources/views/chapter.html",
"layout": "resources/views/layout.html",
"lab": "handlers/lab.go",
"lab-view": "resources/views/lab.html",
}
func Source(sources fs.FS) web.Handler {
return func(r *web.Request) *web.Response {
path, ok := sourcePaths[r.PathValue("name")]
if !ok {
return NotFound(r)
}
body, err := fs.ReadFile(sources, path)
if err != nil {
return web.Fail(err)
}
return web.View("source", page{Title: path, SourcePath: path, SourceCode: string(body)})
}
}
func NotFound(*web.Request) *web.Response {
return web.View("not-found", page{Title: "ページが見つかりません"}).WithStatus(http.StatusNotFound)
}