add description & image for articles

This commit is contained in:
2025-12-23 17:50:55 +03:00
parent 869a513773
commit cdc68c1b53
4 changed files with 120 additions and 24 deletions

View File

@@ -36,13 +36,15 @@ type User struct {
}
type Article struct {
ID int64 `json:"id" db:"id"`
Title string `json:"title" db:"title"`
URL string `json:"url" db:"url"`
Body []byte `json:"-" db:"body"`
UserID int64 `json:"-" db:"user_id"`
CreatedAt string `json:"created_at" db:"created_at"`
UpdatedAt string `json:"updated_at" db:"updated_at"`
ID int64 `json:"id" db:"id"`
Title string `json:"title" db:"title"`
URL string `json:"url" db:"url"`
Body []byte `json:"-" db:"body"`
Description *string `json:"description" db:"description"`
Image *[]byte `json:"image" db:"image"`
UserID int64 `json:"-" db:"user_id"`
CreatedAt string `json:"created_at" db:"created_at"`
UpdatedAt string `json:"updated_at" db:"updated_at"`
}
func readJSON(r *http.Request, s any) error {
@@ -121,6 +123,15 @@ func getUserIdFromRequest(r *http.Request) (int64, error) {
return userId, nil
}
func downloadImage(url string) ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}
type AuthResponse struct {
AccessToken string `json:"access_token"`
}
@@ -317,7 +328,7 @@ func main() {
return
}
title, html, err := app.FetchArticleHTML(body.URL)
page, err := app.FetchArticleHTML(body.URL)
if err != nil {
sendApiError(w, "couldn't fetch article", err, 500)
return
@@ -325,10 +336,19 @@ func main() {
var b bytes.Buffer
gw := gzip.NewWriter(&b)
gw.Write([]byte(html))
gw.Write([]byte(page.Body))
gw.Close()
res, err := db.Exec("INSERT INTO articles (title, url, body, user_id) VALUES (?, ?, ?, ?)", title, body.URL, b.Bytes(), userId)
var imgData []byte
if page.ImageURL != "" {
imgData, err = downloadImage(page.ImageURL)
if err != nil {
sendApiError(w, "couldn't download image from url", err, 500)
return
}
}
res, err := db.Exec("INSERT INTO articles (title, url, description, image, body, user_id) VALUES (?, ?, ?, ?, ?, ?)", page.Title, body.URL, page.Description, imgData, b.Bytes(), userId)
if err != nil {
sendApiError(w, "couldn't save article", err, 500)
return