Micropub endpoint for my blog https://jlelse.blog/posts/hugo-micropub/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.0KB

  1. package main
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "io/ioutil"
  6. "net/http"
  7. )
  8. type ItemList struct {
  9. Items []*MicroformatItem `json:"items"`
  10. }
  11. func QueryURL(url string, limit int) ([]byte, error) {
  12. if len(url) == 0 {
  13. url = BlogUrl
  14. }
  15. if url == BlogUrl {
  16. allPosts, err := allPosts(url)
  17. if err != nil {
  18. return nil, err
  19. }
  20. itemList := &ItemList{}
  21. for i, postURL := range allPosts {
  22. if limit != 0 && i == limit {
  23. break
  24. }
  25. item, _ := getItem(postURL)
  26. itemList.Items = append(itemList.Items, item)
  27. }
  28. jsonBytes, err := json.Marshal(itemList)
  29. if err != nil {
  30. err = errors.New("failed to marshal json")
  31. return nil, err
  32. }
  33. return jsonBytes, err
  34. } else {
  35. item, err := getItem(url)
  36. if err != nil {
  37. return nil, err
  38. }
  39. jsonBytes, err := json.Marshal(item)
  40. if err != nil {
  41. err = errors.New("failed to marshal json")
  42. return nil, err
  43. }
  44. return jsonBytes, err
  45. }
  46. }
  47. func getItem(url string) (item *MicroformatItem, err error) {
  48. entry, err := ReadEntry(url)
  49. if err != nil {
  50. return
  51. }
  52. item = &MicroformatItem{
  53. Type: []string{"h-entry"},
  54. Properties: &MicroformatProperties{
  55. Name: []string{entry.title},
  56. Published: []string{entry.date},
  57. Updated: []string{entry.lastmod},
  58. Category: entry.tags,
  59. Content: []string{entry.content},
  60. Url: []string{entry.location},
  61. },
  62. }
  63. return
  64. }
  65. func allPosts(url string) ([]string, error) {
  66. jsonFeed := &struct {
  67. Items []struct {
  68. Url string `json:"url"`
  69. } `json:"items"`
  70. }{}
  71. resp, err := http.Get(url + "feed.json")
  72. if err != nil {
  73. return nil, errors.New("failed to get json feed")
  74. }
  75. defer resp.Body.Close()
  76. body, err := ioutil.ReadAll(resp.Body)
  77. if err != nil {
  78. return nil, errors.New("failed to read json feed")
  79. }
  80. err = json.Unmarshal(body, &jsonFeed)
  81. if err != nil {
  82. return nil, errors.New("failed to parse json feed")
  83. }
  84. var allUrls []string
  85. for _, item := range jsonFeed.Items {
  86. allUrls = append(allUrls, item.Url)
  87. }
  88. return allUrls, nil
  89. }