hmn/src/website/routes.go

89 lines
1.9 KiB
Go
Raw Normal View History

2021-03-14 20:49:58 +00:00
package website
import (
"context"
"fmt"
"net/http"
"git.handmade.network/hmn/hmn/src/logging"
"git.handmade.network/hmn/hmn/src/templates"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/julienschmidt/httprouter"
)
type websiteRoutes struct {
2021-03-18 02:14:06 +00:00
*HMNRouter
2021-03-14 20:49:58 +00:00
conn *pgxpool.Pool
}
func NewWebsiteRoutes(conn *pgxpool.Pool) http.Handler {
routes := &websiteRoutes{
2021-03-18 02:14:06 +00:00
HMNRouter: &HMNRouter{HttpRouter: httprouter.New()},
conn: conn,
2021-03-14 20:49:58 +00:00
}
routes.GET("/", routes.Index)
routes.GET("/project/:id", routes.Project)
routes.GET("/assets/project.css", routes.ProjectCSS)
2021-03-18 01:25:06 +00:00
routes.ServeFiles("/public/*filepath", http.Dir("public"))
2021-03-14 20:49:58 +00:00
return routes
}
2021-03-18 02:14:06 +00:00
func (s *websiteRoutes) Index(c *RequestContext, p httprouter.Params) {
err := c.WriteTemplate("index.html", templates.BaseData{
2021-03-18 01:25:06 +00:00
Project: templates.Project{
Name: "Handmade Network",
Color: "cd4e31",
IsHMN: true,
HasBlog: true,
HasForum: true,
HasWiki: true,
HasLibrary: true,
},
Theme: "dark",
2021-03-14 20:49:58 +00:00
})
if err != nil {
panic(err)
}
}
2021-03-18 02:14:06 +00:00
func (s *websiteRoutes) Project(c *RequestContext, p httprouter.Params) {
2021-03-14 20:49:58 +00:00
id := p.ByName("id")
row := s.conn.QueryRow(context.Background(), "SELECT name FROM handmade_project WHERE id = $1", p.ByName("id"))
var name string
err := row.Scan(&name)
if err != nil {
panic(err)
}
2021-03-18 02:14:06 +00:00
c.Body.Write([]byte(fmt.Sprintf("(%s) %s\n", id, name)))
2021-03-14 20:49:58 +00:00
}
2021-03-18 02:14:06 +00:00
func (s *websiteRoutes) ProjectCSS(c *RequestContext, p httprouter.Params) {
color := c.URL().Query().Get("color")
2021-03-14 20:49:58 +00:00
if color == "" {
2021-03-18 02:14:06 +00:00
c.StatusCode = http.StatusBadRequest
c.Body.Write([]byte("You must provide a 'color' parameter.\n"))
2021-03-14 20:49:58 +00:00
return
}
templateData := struct {
Color string
Theme string
}{
Color: color,
Theme: "dark",
}
2021-03-18 02:14:06 +00:00
c.Headers().Add("Content-Type", "text/css")
err := c.WriteTemplate("project.css", templateData)
2021-03-14 20:49:58 +00:00
if err != nil {
logging.Error().Err(err).Msg("failed to generate project CSS")
return
}
}