friend/handlers.go

106 lines
2.8 KiB
Go

package main
import (
"encoding/json"
"net/http"
"github.com/go-chi/chi/v5"
)
type APIError struct {
Error string `json:"error"`
}
// since we only have the single username to worry about, we just wrap everything up here
func UserExistsMiddleware(user string, h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userID := chi.URLParam(r, "user")
if userID != user {
RespondJSON(w, APIError{Error: "account not found"}, http.StatusNotFound)
return
}
h.ServeHTTP(w, r)
}
}
func RespondJSON(w http.ResponseWriter, content any, statuscode int) {
b, err := json.Marshal(content)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(statuscode)
w.Write(b)
}
func WebFingerHandler(wf *Webfinger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
requestedResource := r.URL.Query().Get("resource")
res, err := wf.FingerResource(requestedResource)
if err != nil {
RespondJSON(w, APIError{Error: "account not found"}, http.StatusNotFound)
return
}
RespondJSON(w, res, http.StatusOK)
}
}
func ProfileHandler(pp *ProfileProvider) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
res, err := pp.Get()
if err != nil {
RespondJSON(w, APIError{Error: "account not found"}, http.StatusNotFound)
return
}
RespondJSON(w, res, http.StatusOK)
}
}
// client retrieves messages for user
func GetInboxHandler(streams *InMemoryStreams) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
stream, err := streams.GetActivitiesToUser()
if err != nil {
RespondJSON(w, APIError{Error: err.Error()}, http.StatusInternalServerError)
return
}
RespondJSON(w, stream, http.StatusOK)
}
}
// handle incoming activities for user
func PostInboxHandler(streams *InMemoryStreams) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
err := streams.AddActivityToUser()
if err != nil {
RespondJSON(w, APIError{Error: err.Error()}, http.StatusInternalServerError)
return
}
RespondJSON(w, nil, http.StatusOK)
}
}
// other servers/clients read a user's activities
func GetOutboxHandler(streams *InMemoryStreams) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
stream, err := streams.GetActivitiesFromUser()
if err != nil {
RespondJSON(w, APIError{Error: err.Error()}, http.StatusInternalServerError)
return
}
RespondJSON(w, stream, http.StatusOK)
}
}
// client adds new activity for user
func PostOutboxHandler(streams *InMemoryStreams) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
err := streams.AddActivityFromUser()
if err != nil {
RespondJSON(w, APIError{Error: err.Error()}, http.StatusInternalServerError)
return
}
RespondJSON(w, nil, http.StatusOK)
}
}