From 9b954ac06248e46541d19025ca87f9f043e5e2e2 Mon Sep 17 00:00:00 2001 From: Elizabeth Hunt Date: Sun, 5 Jan 2025 17:30:36 -0800 Subject: [PATCH] set cors --- api/api.go | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/api/api.go b/api/api.go index 43dd476..391183c 100644 --- a/api/api.go +++ b/api/api.go @@ -60,6 +60,13 @@ func SetJsonContinuation(context *types.RequestContext, req *http.Request, resp } } +func SetCorsContinuation(context *types.RequestContext, req *http.Request, resp http.ResponseWriter) types.ContinuationChain { + return func(success types.Continuation, _failure types.Continuation) types.ContinuationChain { + resp.Header().Set("Access-Control-Allow-Origin", "*") + return success(context, req, resp) + } +} + func CacheControlMiddleware(next http.Handler, maxAge int) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { header := fmt.Sprintf("public, max-age=%d", maxAge) @@ -68,6 +75,15 @@ func CacheControlMiddleware(next http.Handler, maxAge int) http.Handler { }) } +// basically b(a(message)) if and only if b is successful +func Compose(a types.Continuation, b types.Continuation) types.Continuation { + return func(context *types.RequestContext, req *http.Request, resp http.ResponseWriter) types.ContinuationChain { + return func(success types.Continuation, failure types.Continuation) types.ContinuationChain { + return b(context, req, resp)(a, FailurePassingContinuation)(success, failure) + } + } +} + func MakeMux(argv *args.Arguments, dbConn *sql.DB) *http.ServeMux { mux := http.NewServeMux() @@ -95,8 +111,8 @@ func MakeMux(argv *args.Arguments, dbConn *sql.DB) *http.ServeMux { mux.HandleFunc("GET /updates", func(w http.ResponseWriter, r *http.Request) { requestContext := makeRequestContext() - - LogRequestContinuation(requestContext, r, w)(whois.ListUpdates, FailurePassingContinuation)(SetJsonContinuation, FailurePassingContinuation)(template.TemplateContinuation("updates.json.tmpl", false), FailurePassingContinuation)(LogExecutionTimeContinuation, LogExecutionTimeContinuation)(IdContinuation, IdContinuation) + continuation := Compose(template.TemplateContinuation("updates.json.tmpl", false), Compose(whois.ListUpdates, Compose(SetJsonContinuation, SetCorsContinuation))) + LogRequestContinuation(requestContext, r, w)(continuation, FailurePassingContinuation)(LogExecutionTimeContinuation, LogExecutionTimeContinuation)(IdContinuation, IdContinuation) }) return mux