api.go (931B)
1 package api 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "net/http" 7 8 "github.com/charmbracelet/bubbletea" 9 ) 10 11 type PageMsg []Post 12 type PostMsg Post 13 type ErrorMsg error 14 15 func FetchPage(index int) tea.Cmd { 16 return func() tea.Msg { 17 posts, err := page(index) 18 if err != nil { 19 return ErrorMsg(err) 20 } 21 22 return PageMsg(posts) 23 } 24 } 25 26 func FetchPost(id string) tea.Cmd { 27 return func() tea.Msg { 28 resp, err := http.Get(fmt.Sprintf("https://lobste.rs/s/%s.json", id)) 29 if err != nil { 30 return ErrorMsg(err) 31 } 32 defer resp.Body.Close() 33 34 var post Post 35 err = json.NewDecoder(resp.Body).Decode(&post) 36 if err != nil { 37 return ErrorMsg(err) 38 } 39 return PostMsg(post) 40 } 41 } 42 43 func page(i int) ([]Post, error) { 44 resp, err := http.Get(fmt.Sprintf("https://lobste.rs/page/%d.json", i)) 45 if err != nil { 46 return nil, err 47 } 48 defer resp.Body.Close() 49 50 var posts []Post 51 err = json.NewDecoder(resp.Body).Decode(&posts) 52 return posts, err 53 }