101 lines
2.6 KiB
Go
101 lines
2.6 KiB
Go
package gemlog
|
|
|
|
import (
|
|
_ "embed"
|
|
"fmt"
|
|
"log/slog"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
|
|
gemlog "git.travisshears.com/travisshears/gemlog-cli/gemlog"
|
|
gemini "github.com/kulak/gemini"
|
|
)
|
|
|
|
type Gemlog struct {
|
|
config *gemlog.Config
|
|
}
|
|
|
|
func NewGemlog() *Gemlog {
|
|
port, err := strconv.Atoi(os.Getenv("COUCH_DB_PORT"))
|
|
if err != nil {
|
|
slog.Error("Failed to parse COUCH_DB_PORT", "error", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
config := gemlog.Config{
|
|
CouchDB: gemlog.CouchDBConfig{
|
|
Host: os.Getenv("COUCHDB_HOST"),
|
|
Port: port,
|
|
User: os.Getenv("COUCHDB_USER"),
|
|
Password: os.Getenv("COUCHDB_PASSWORD"),
|
|
},
|
|
}
|
|
|
|
g := &Gemlog{
|
|
config: &config,
|
|
}
|
|
return g
|
|
}
|
|
|
|
func (g *Gemlog) HandleRequest(w gemini.ResponseWriter, req *gemini.Request) {
|
|
path := req.URL.Path
|
|
|
|
switch {
|
|
case path == "/gemlog" || path == "/gemlog/":
|
|
g.serveIndex(w, req)
|
|
case strings.HasPrefix(path, "/gemlog/post/"):
|
|
slug := strings.TrimPrefix(path, "/gemlog/post/")
|
|
g.servePost(w, req, slug)
|
|
default:
|
|
w.WriteStatusMsg(gemini.StatusNotFound, "Page not found")
|
|
}
|
|
}
|
|
|
|
//go:embed gemlog.gmi
|
|
var pageContnet string
|
|
|
|
func (g *Gemlog) serveIndex(w gemini.ResponseWriter, req *gemini.Request) {
|
|
w.WriteStatusMsg(gemini.StatusSuccess, "text/gemini")
|
|
|
|
var content strings.Builder
|
|
content.Write([]byte(pageContnet))
|
|
content.WriteString("\n")
|
|
|
|
posts, err := gemlog.ListGemLogs(g.config)
|
|
if err != nil {
|
|
content.WriteString("Error fetching posts: " + err.Error() + "\n\n")
|
|
}
|
|
|
|
if len(posts) == 0 {
|
|
content.WriteString("No posts found.\n\n")
|
|
} else {
|
|
content.WriteString("## Posts\n\n")
|
|
|
|
for _, post := range posts {
|
|
content.WriteString(fmt.Sprintf("=> /gemlog/post/%s %s - %s\n", post.Slug, post.Date.Format("2006-01-02"), post.Title))
|
|
}
|
|
}
|
|
|
|
content.WriteString("## Nav\n\n")
|
|
// content.WriteString(fmt.Sprintf("=> /microblog/page/%d Next page\n", pageNum+1))
|
|
content.WriteString("=> / Back to home\n")
|
|
w.WriteBody([]byte(content.String()))
|
|
}
|
|
|
|
func (g *Gemlog) servePost(w gemini.ResponseWriter, req *gemini.Request, slug string) {
|
|
var content strings.Builder
|
|
w.WriteStatusMsg(gemini.StatusSuccess, "text/gemini")
|
|
post, err := gemlog.ReadGemlogEntryBySlug(g.config, slug)
|
|
if err != nil {
|
|
content.WriteString("Error fetching gemlog post: " + err.Error() + "\n\n")
|
|
}
|
|
|
|
content.WriteString(fmt.Sprintf("# %s\n", post.Title))
|
|
content.WriteString(fmt.Sprintf("posted: %s\n", post.Date.Format("2006-01-02")))
|
|
content.WriteString(post.Gemtxt)
|
|
content.WriteString("## Nav\n\n")
|
|
content.WriteString("=> /gemlog Back to gemlog list\n")
|
|
content.WriteString("=> / Back to home\n")
|
|
w.WriteBody([]byte(content.String()))
|
|
}
|