lab-development-imb/web/07/labor/loesungen_07/Kommandozeilenprogramm/book.go

80 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package main
import (
"encoding/json"
"fmt"
"os"
)
type Book struct {
ID int `json:"id"`
Titel string `json:"titel"`
Autor string `json:"autor"`
Read bool `json:"read"`
}
type Library struct {
Books []Book `json:"books"`
}
// fügt ein Buch der Library hinzu
func (l *Library) Add(titel, autor string) {
id := len(l.Books) + 1
newBook := Book{ID: id, Titel: titel, Autor: autor, Read: false}
l.Books = append(l.Books, newBook)
}
// Markiert ein Buch als gelesen
func (l *Library) Read(id int) {
for i := range l.Books {
if l.Books[i].ID == id {
l.Books[i].Read = true
}
}
}
// Listet alle Bücher auf
func (l *Library) List() {
if len(l.Books) == 0 {
fmt.Println("Keine Bücher vorhanden.")
return
}
for _, b := range l.Books {
status := "ungelesen"
if b.Read {
status = "gelesen"
}
fmt.Printf("%d: %s (%s) %s\n", b.ID, b.Titel, b.Autor, status)
}
}
// Liste als JSON speichern
func (l *Library) Save(filename string) error {
data, err := json.MarshalIndent(l, "", " ")
if err != nil {
return err
}
err = os.WriteFile(filename, data, 0644)
if err != nil {
return err
}
return nil
}
// JSON aus Datei laden
func Load(filename string) (*Library, error) {
data, err := os.ReadFile(filename)
if err != nil {
if os.IsNotExist(err) {
return &Library{}, nil
}
return nil, err
}
var l Library
jsonErr := json.Unmarshal(data, &l)
return &l, jsonErr
}