This commit is contained in:
2024-10-21 09:34:38 +00:00
parent 78b8ebf5bf
commit c7e45139ec
9 changed files with 201 additions and 22 deletions

3
structs-practice/go.mod Normal file
View File

@@ -0,0 +1,3 @@
module example.com/note
go 1.23.1

55
structs-practice/main.go Normal file
View File

@@ -0,0 +1,55 @@
package main
import (
"bufio"
"fmt"
"example.com/note/note"
"os"
"strings"
)
func main() {
title, content := getNoteData()
userNote, err := note.New(title, content)
if err != nil {
fmt.Println(err)
return
}
userNote.Display()
err = userNote.Save()
if err != nil {
fmt.Println("Saving the note failed")
return
}
fmt.Println("Saving the note succeeded!")
}
func getNoteData() (string, string) {
title := getUserInput("Note title:")
content := getUserInput("Note content:")
return title, content
}
func getUserInput(prompt string) (string) {
fmt.Printf("%v ", prompt)
reader := bufio.NewReader(os.Stdin)
text, err :=reader.ReadString('\n')
if err != nil {
return ""
}
text = strings.TrimSuffix(text, "\n")
text = strings.TrimSuffix(text, "\r")
return text
}

View File

@@ -0,0 +1,45 @@
package note
import (
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"time"
)
type Note struct {
Title string `json:"title"`
Content string `json:"content"`
CreatedAt time.Time `json:"created_at"`
}
func (note Note) Display() {
fmt.Printf("Your note title %v has the following content:\n\n%v", note.Title, note.Content)
}
func (note Note) Save() error {
fileName := strings.ReplaceAll(note.Title, " ", "_")
fileName = strings.ToLower(fileName) + ".json"
json, err := json.Marshal(note)
if err != nil {
return err
}
return os.WriteFile(fileName, json, 0644)
}
func New(title, content string) (Note, error) {
if title == "" || content == "" {
return Note{}, errors.New("Invalid input")
}
return Note{
Title: title,
Content: content,
CreatedAt: time.Now(),
}, nil
}