From e2fc96d90283e9462c11c05d4d50519a9fcf066b Mon Sep 17 00:00:00 2001 From: matthieugouel Date: Sun, 1 Dec 2024 11:14:52 +0100 Subject: [PATCH] Fix `allow_cors: true` returning two `Access-Control-Allow-Origin` headers Fixes #93. The `Access-Control-Allow-Origin` was set before on the response before the proxy call, and ClickHouse was returning the response with its own `Access-Control-Allow-Origin` (in my case, "*"). So, having `allow_cors: true` was eventually returning two `Access-Control-Allow-Origin`, one from chproxy and one from ClickHouse. This commit just move the `"Access-Control-Allow-Origin` after the proxy call, overriding the value returned by ClickHouse. If `allow_cors: false`, chproxy does not change the value (so it can be, I believe, any value set by ClickHouse), else, with `allow_cors: true`, it will override to either the value of `Origin` request if any or else `*`. --- proxy.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/proxy.go b/proxy.go index 15ca73ea..c02dbd8a 100644 --- a/proxy.go +++ b/proxy.go @@ -107,14 +107,6 @@ func (rp *reverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) { log.Debugf("%s: request start", s) requestSum.With(s.labels).Inc() - if s.user.allowCORS { - origin := req.Header.Get("Origin") - if len(origin) == 0 { - origin = "*" - } - rw.Header().Set("Access-Control-Allow-Origin", origin) - } - req.Body = &statReadCloser{ ReadCloser: req.Body, bytesRead: requestBodyBytes.With(s.labels), @@ -149,6 +141,14 @@ func (rp *reverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) { rp.proxyRequest(s, srw, srw, req) } + if s.user.allowCORS { + origin := req.Header.Get("Origin") + if len(origin) == 0 { + origin = "*" + } + rw.Header().Set("Access-Control-Allow-Origin", origin) + } + // It is safe calling getQuerySnippet here, since the request // has been already read in proxyRequest or serveFromCache. query := getQuerySnippet(req)