Moved away from local files to complete database driven articles
This commit is contained in:
60
api/upload.go
Normal file
60
api/upload.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"TheAdversary/database"
|
||||
"TheAdversary/parse"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"go.uber.org/zap"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type uploadRequest struct {
|
||||
Name string
|
||||
Author string
|
||||
Title string
|
||||
Summary string
|
||||
Image string
|
||||
Tags []string
|
||||
Content string
|
||||
}
|
||||
|
||||
func Upload(w http.ResponseWriter, r *http.Request) {
|
||||
var request uploadRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
InvalidJson.Send(w)
|
||||
return
|
||||
}
|
||||
|
||||
rawMarkdown, err := base64.StdEncoding.DecodeString(request.Content)
|
||||
if err != nil {
|
||||
zap.S().Warnf("Cannot decode base64")
|
||||
ApiError{Message: "invalid base64 content", Code: http.StatusUnprocessableEntity}.Send(w)
|
||||
return
|
||||
}
|
||||
|
||||
db := database.GetDB()
|
||||
|
||||
tags, err := db.AddOrGetTags(request.Tags)
|
||||
if err != nil {
|
||||
zap.S().Error("Failed to add or get tag to / from database: %v", err)
|
||||
DatabaseError.Send(w)
|
||||
return
|
||||
}
|
||||
if err = db.AddArticle(database.Article{
|
||||
Name: request.Name,
|
||||
Title: request.Title,
|
||||
Summary: request.Summary,
|
||||
Image: request.Image,
|
||||
Added: time.Now().Unix(),
|
||||
Markdown: request.Content,
|
||||
Html: string(parse.ParseToHtml(rawMarkdown)),
|
||||
}, tags); err != nil {
|
||||
zap.S().Errorf("Failed to add article to database: %v", err)
|
||||
DatabaseError.Send(w)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
Reference in New Issue
Block a user