73 lines
2.0 KiB
Go
73 lines
2.0 KiB
Go
package database
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/russross/blackfriday/v2"
|
|
)
|
|
|
|
type Post struct {
|
|
ID int
|
|
Title string `db:"post_title"`
|
|
Content string
|
|
Date string
|
|
MarkdownContent string `db:"markdown_content"`
|
|
GemtextContent sql.NullString `db:"gemtext_content"`
|
|
TitleSlug string `db:"title_slug"`
|
|
Year, Month, Day int
|
|
}
|
|
|
|
func (p *Post) GemtextPage() string {
|
|
return fmt.Sprintf("# %s\n\n", p.Title) + p.GemtextContent.String + "\n\n" + p.Date
|
|
|
|
}
|
|
|
|
func (p *Post) HTMLPage() string {
|
|
extensions := blackfriday.CommonExtensions | blackfriday.HardLineBreak
|
|
result := fmt.Sprintf("<h1>%s</h1>\n%s", p.Title, blackfriday.Run([]byte(p.MarkdownContent), blackfriday.WithExtensions(extensions)))
|
|
result += fmt.Sprintf("%s", p.Date)
|
|
return result
|
|
}
|
|
|
|
func GetPost(id int) (*Post, error) {
|
|
db := GetDB()
|
|
post := &Post{}
|
|
err := db.Get(post, "SELECT id, post_title, date, markdown_content, gemtext_content, title_slug, year, month, day FROM posts WHERE id = ? and gemtext_content is not null", id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return post, nil
|
|
}
|
|
|
|
func UpdatePost(p *Post) error {
|
|
db := GetDB()
|
|
_, err := db.Exec("UPDATE posts SET post_title = ?, markdown_content = ?, gemtext_content = ?, title_slug = ?, year = ?, month = ?, day = ? WHERE id = ?", p.Title, p.MarkdownContent, p.GemtextContent, p.TitleSlug, p.Year, p.Month, p.Day, p.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func CreateNewPost() (*Post, error) {
|
|
db := GetDB()
|
|
day := time.Now().Day()
|
|
month := time.Now().Month()
|
|
year := time.Now().Year()
|
|
|
|
result, err := db.Exec("INSERT INTO posts (post_title, markdown_content, gemtext_content, title_slug, year, month, day) VALUES (?, ?, ?, ?, ?, ?, ?)", "Novi Clanak", "", "", "new-post", year, month, day)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
postID, err := result.LastInsertId()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
post, err := GetPost(int(postID))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return post, nil
|
|
}
|