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.
 
 

75 lines
2.1 KiB

  1. package main
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. )
  6. type MicropubConfig struct {
  7. SyndicateTo []SyndicationTarget `json:"syndicate-to,omitempty"`
  8. MediaEndpoint string `json:"media-endpoint,omitempty"`
  9. }
  10. func HandleMicroPub(w http.ResponseWriter, r *http.Request) {
  11. // a handler for GET requests, used for troubleshooting
  12. if r.Method == "GET" {
  13. if q := r.URL.Query().Get("q"); q == "config" || q == "syndicate-to" {
  14. w.Header().Add("Content-type", "application/json")
  15. w.WriteHeader(http.StatusOK)
  16. _ = json.NewEncoder(w).Encode(&MicropubConfig{
  17. SyndicateTo: SyndicationTargets,
  18. MediaEndpoint: MediaEndpointUrl,
  19. })
  20. return
  21. } else {
  22. w.Header().Add("Content-type", "application/json")
  23. w.WriteHeader(http.StatusOK)
  24. _, _ = w.Write([]byte("{}"))
  25. return
  26. }
  27. }
  28. // check if the request is a POST
  29. if r.Method != "POST" {
  30. w.WriteHeader(http.StatusMethodNotAllowed)
  31. _, _ = w.Write([]byte("The HTTP method is not allowed, make a POST request"))
  32. return
  33. }
  34. // check content type
  35. contentType, err := GetContentType(r.Header.Get("content-type"))
  36. if err != nil {
  37. w.WriteHeader(http.StatusBadRequest)
  38. _, _ = w.Write([]byte(err.Error()))
  39. return
  40. }
  41. // Create entry
  42. entry, err := CreateEntry(contentType, r)
  43. if err != nil || entry == nil {
  44. w.WriteHeader(http.StatusBadRequest)
  45. if err != nil {
  46. _, _ = w.Write([]byte(err.Error()))
  47. } else {
  48. _, _ = w.Write([]byte("There was an error creating the entry"))
  49. }
  50. return
  51. }
  52. if authHeader := r.Header.Get("authorization"); len(entry.token) == 0 && len(authHeader) > 0 {
  53. entry.token = authHeader
  54. }
  55. if CheckAuthorization(entry.token) {
  56. location, err := WriteEntry(entry)
  57. if err != nil {
  58. w.WriteHeader(http.StatusBadRequest)
  59. _, _ = w.Write([]byte("There was an error committing the entry to the repository"))
  60. return
  61. } else {
  62. w.Header().Add("Location", location+"?cache=0")
  63. w.WriteHeader(http.StatusAccepted)
  64. return
  65. }
  66. } else {
  67. w.WriteHeader(http.StatusForbidden)
  68. _, _ = w.Write([]byte("Forbidden, there was a problem with the provided access token"))
  69. return
  70. }
  71. }