Files
blog/write-go/internal/sessions/sessions.go
T
2026-06-01 17:57:22 +08:00

72 lines
1.4 KiB
Go

package sessions
import (
"sync"
"write-server/pkg/posts"
)
type Session struct {
Title string `json:"title"`
Slug string `json:"slug"`
Content string `json:"content"`
Categories []string `json:"categories"`
Tags []string `json:"tags"`
Author string `json:"author"`
Draft bool `json:"draft"`
}
var mu sync.Mutex
var sessions = make(map[int64]*Session)
func GetSession(chatID int64) *Session {
mu.Lock()
defer mu.Unlock()
if s, ok := sessions[chatID]; ok {
return s
}
s := &Session{Author: "qunlin", Draft: true}
sessions[chatID] = s
return s
}
func ClearSession(chatID int64) {
mu.Lock()
defer mu.Unlock()
delete(sessions, chatID)
}
func HasSession(chatID int64) bool {
mu.Lock()
defer mu.Unlock()
_, ok := sessions[chatID]
return ok
}
func Save(s *Session, isDraft bool) error {
fm := posts.FrontMatter{
Title: s.Title,
Slug: s.Slug,
Draft: isDraft,
Categories: s.Categories,
Tags: s.Tags,
Author: s.Author,
Layout: "post",
}
existing := posts.GetPost(s.Slug)
if existing != nil {
updates := map[string]interface{}{}
updates["title"] = s.Title
updates["draft"] = isDraft
updates["categories"] = s.Categories
updates["tags"] = s.Tags
updates["author"] = s.Author
_, err := posts.UpdatePost(s.Slug, updates, &s.Content)
return err
}
_, err := posts.CreatePost(fm, s.Content)
return err
}