hugo-micropub/main.go

96 lines
2.5 KiB
Go
Raw Normal View History

2019-11-07 10:00:24 +00:00
package main
import (
"log"
"net/http"
2019-11-14 17:46:49 +00:00
"strconv"
2019-11-07 10:00:24 +00:00
"time"
)
func handleMicroPub(w http.ResponseWriter, r *http.Request) {
// a handler for GET requests, used for troubleshooting
if r.Method == "GET" {
if q := r.URL.Query().Get("q"); q == "syndicate-to" {
w.Header().Add("Content-type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("[]"))
return
2019-11-14 17:46:49 +00:00
} else if url := r.URL.Query().Get("url"); q == "source" {
limit := r.URL.Query().Get("limit")
limitInt, err := strconv.Atoi(limit)
jsonBytes, err := QueryURL(url, limitInt)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(err.Error()))
return
}
w.Header().Add("Content-type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(jsonBytes)
return
2019-11-07 10:00:24 +00:00
} else {
w.Header().Add("Content-type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("{}"))
return
}
}
// check if the request is a POST
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
_, _ = w.Write([]byte("The HTTP method is not allowed, make a POST request"))
return
}
// check content type
contentType, err := GetContentType(r.Header.Get("content-type"))
if err != nil {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(err.Error()))
return
}
// Create entry
2019-11-07 11:10:45 +00:00
entry, err := CreateEntry(contentType, r)
if err != nil || entry == nil {
2019-11-07 10:00:24 +00:00
w.WriteHeader(http.StatusBadRequest)
if err != nil {
_, _ = w.Write([]byte(err.Error()))
} else {
_, _ = w.Write([]byte("There was an error creating the entry"))
}
2019-11-07 10:00:24 +00:00
return
}
if CheckAuthorization(entry, r.Header.Get("authorization")) {
location, err := WriteEntry(entry)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte("There was an error committing the entry to the repository"))
return
} else {
w.Header().Add("Location", location)
w.WriteHeader(http.StatusAccepted)
// Purge BunnyCDN in 10 seconds
go func() {
time.Sleep(10 * time.Second)
Purge(location)
2019-12-03 17:12:10 +00:00
// Send webmentions
go func() {
time.Sleep(3 * time.Second)
SendWebmentions(location)
}()
}()
2019-11-07 10:00:24 +00:00
return
}
} else {
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte("Forbidden, there was a problem with the provided access token"))
return
}
}
func main() {
http.HandleFunc("/", handleMicroPub)
log.Println("Starting micropub server...")
log.Println("Current time: " + time.Now().Format(time.RFC3339))
log.Fatal(http.ListenAndServe(":5555", nil))
}