1
0
mirror of https://github.com/JustKato/FreePad.git synced 2026-02-23 15:50:46 +02:00

+ Handle post data

This commit is contained in:
2022-05-20 01:40:21 +03:00
parent a76b9d02ba
commit 051a8a311c
8 changed files with 154 additions and 27 deletions

View File

@@ -6,8 +6,9 @@ import (
)
type Post struct {
Name string `json:"name"`
Content string `json:"content"`
Name string `json:"name"`
LastModified string `json:"last_modified"`
Content string `json:"content"`
}
func getStorageDirectory() string {
@@ -39,16 +40,14 @@ func GetPost(fileName string) Post {
// Generate the file path
filePath := fmt.Sprintf("%s%s", storageDir, fileName)
fmt.Println("Reading: ", filePath)
p := Post{
Name: fileName,
Content: "",
Name: fileName,
Content: "",
LastModified: "Never Before",
}
// Check if the file exits
if _, err := os.Stat(filePath); !os.IsNotExist(err) {
fmt.Println("Found ", filePath)
// File does exist, read it and set the content
data, err := os.ReadFile(filePath)
if err != nil {
@@ -57,7 +56,14 @@ func GetPost(fileName string) Post {
// Get the content of the file and put it in the response
p.Content = string(data)
fmt.Println("Loaded content for ", filePath)
// Get last modified date
fileData, err := os.Stat(filePath)
if err == nil {
p.LastModified = fileData.ModTime().Format("02/01/2006 03:04:05 PM")
} else {
fmt.Println(err)
}
}
return p
@@ -65,5 +71,26 @@ func GetPost(fileName string) Post {
func WritePost(p Post) error {
// Get the base storage directory and make sure it exists
storageDir := getStorageDirectory()
// Generate the file path
filePath := fmt.Sprintf("%s%s", storageDir, p.Name)
f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
if err != nil {
return err
}
// Write the contnets
_, err = f.WriteString(p.Content)
if err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
return nil
}