106 lines
1.8 KiB
Go
106 lines
1.8 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"bytes"
|
||
|
"encoding/json"
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
"io"
|
||
|
"net/http"
|
||
|
)
|
||
|
|
||
|
type note struct {
|
||
|
Id int64 `json:"id"`
|
||
|
Title string `json:"title"`
|
||
|
Content string `json:"content"`
|
||
|
}
|
||
|
|
||
|
const endpoint = "http://localhost:8080/api"
|
||
|
|
||
|
func loadNotes() ([]note, error) {
|
||
|
res, err := http.Get(endpoint + "/notes")
|
||
|
if err != nil {
|
||
|
return []note{}, nil
|
||
|
}
|
||
|
|
||
|
data, err := io.ReadAll(res.Body)
|
||
|
if err != nil {
|
||
|
return []note{}, nil
|
||
|
}
|
||
|
|
||
|
var loadedNotes []note
|
||
|
json.Unmarshal(data, &loadedNotes)
|
||
|
return loadedNotes, nil
|
||
|
}
|
||
|
|
||
|
func putNote(n note) error {
|
||
|
json, err := json.Marshal(n)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
req, err := http.NewRequest("PUT", endpoint+"/notes/"+fmt.Sprint(n.Id), bytes.NewReader(json))
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
req.Header.Add("Content-Type", "application/json")
|
||
|
|
||
|
res, err := http.DefaultClient.Do(req)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
if res.StatusCode != http.StatusOK {
|
||
|
return errors.New("Request failed: " + res.Status)
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func postNote(n note) (note, error) {
|
||
|
jsonBytes, err := json.Marshal(n)
|
||
|
if err != nil {
|
||
|
return note{}, err
|
||
|
}
|
||
|
|
||
|
res, err := http.Post(endpoint+"/notes", "application/json", bytes.NewReader(jsonBytes))
|
||
|
if err != nil {
|
||
|
return note{}, err
|
||
|
}
|
||
|
|
||
|
if res.StatusCode != http.StatusCreated {
|
||
|
return note{}, errors.New("Request failed: " + res.Status)
|
||
|
}
|
||
|
|
||
|
resBytes, err := io.ReadAll(res.Body)
|
||
|
if err != nil {
|
||
|
return note{}, err
|
||
|
}
|
||
|
|
||
|
err = json.Unmarshal(resBytes, &n)
|
||
|
if err != nil {
|
||
|
return note{}, err
|
||
|
}
|
||
|
|
||
|
return n, nil
|
||
|
}
|
||
|
|
||
|
func deleteNote(n note) error {
|
||
|
req, err := http.NewRequest("DELETE", endpoint+"/notes/"+fmt.Sprint(n.Id), bytes.NewReader([]byte{}))
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
res, err := http.DefaultClient.Do(req)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
if res.StatusCode != http.StatusOK {
|
||
|
return errors.New("Request failed: " + res.Status)
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|