lab-development-imb/web/07/labor/loesungen/uebung02/book.go

49 lines
924 B
Go

package main
import (
"encoding/json"
"os"
)
type Book struct {
ID int `json:"id"`
Title string `json:"title"`
Author string `json:"author"`
Read bool `json:"read"`
}
type Library struct {
Books []Book `json:"books"`
}
func (lib *Library) Add(title, author string) {
id := len(lib.Books) + 1
lib.Books = append(lib.Books, Book{ID: id, Title: title, Author: author, Read: false})
}
func (lib *Library) MarkRead(id int) {
for i := range lib.Books {
if lib.Books[i].ID == id {
lib.Books[i].Read = true
}
}
}
func (lib *Library) Save(filename string) error {
data, err := json.MarshalIndent(lib, "", " ")
if err != nil {
return err
}
return os.WriteFile(filename, data, 0644)
}
func LoadLibrary(filename string) (*Library, error) {
data, err := os.ReadFile(filename)
if err != nil {
return &Library{}, nil
}
var lib Library
err = json.Unmarshal(data, &lib)
return &lib, err
}