MCPcopy Create free account
hub / github.com/bcspragu/logseq-sync / toHandleFunc

Function toHandleFunc

cmd/server/main.go:900–945  ·  view source on GitHub ↗
(fn func(context.Context, *Q) (*S, error))

Source from the content-addressed store, hash-verified

898}
899
900func toHandleFunc[Q any, S any](fn func(context.Context, *Q) (*S, error)) http.HandlerFunc {
901 return func(w http.ResponseWriter, r *http.Request) {
902 log.Println(r.URL.Path)
903 if r.Method != http.MethodPost {
904 handleError(w, httperr.MethodNotAllowed("request to %q had invalid method", r.URL.Path))
905 return
906 }
907
908 ctx := context.WithValue(r.Context(), authContextKey{}, r.Header.Get("Authorization"))
909
910 var req Q
911 var reqA any = req
912 reqI, ok := reqA.(requester)
913 if ok {
914 // Implements custom request parsing, do that.
915 if err := reqI.parseRequest(r); err != nil {
916 handleError(w, httperr.BadRequest("failed to parse custom request: %w", err))
917 return
918 }
919 } else {
920 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
921 handleError(w, httperr.BadRequest("failed to decode request as JSON: %w", err))
922 return
923 }
924 }
925
926 resp, err := fn(ctx, &req)
927 if err != nil {
928 handleError(w, err)
929 return
930 }
931 log.Println(r.URL.Path, "success")
932
933 // If the type implements a custom responder, we should use that.
934 var respA any = resp
935 respI, ok := respA.(responder)
936 if ok {
937 respI.respond(w, r)
938 return
939 }
940
941 if err := json.NewEncoder(w).Encode(resp); err != nil {
942 log.Printf("failed to encode response: %v", err)
943 }
944 }
945}
946
947type requester interface {
948 parseRequest(r *http.Request) error

Callers

nothing calls this directly

Calls 5

MethodNotAllowedFunction · 0.92
BadRequestFunction · 0.92
handleErrorFunction · 0.85
parseRequestMethod · 0.65
respondMethod · 0.65

Tested by

no test coverage detected