gengitkan/internal/route/proxy.go

44 lines
1.1 KiB
Go
Raw Permalink Normal View History

2019-11-28 11:50:51 +01:00
package route
import (
"fmt"
"net/http"
"net/http/httputil"
"net/url"
2020-04-30 10:32:12 +02:00
"forge.cadoles.com/wpetit/gengitkan/internal/config"
"forge.cadoles.com/wpetit/gengitkan/internal/middleware"
2019-11-28 11:50:51 +01:00
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/middleware/container"
"gitlab.com/wpetit/goweb/service/session"
)
func proxyAPIRequest(w http.ResponseWriter, r *http.Request) {
ctn := container.Must(r.Context())
conf := config.Must(ctn)
apiBaseURL, err := url.Parse(conf.Gitea.APIBaseURL)
if err != nil {
panic(errors.Wrap(err, "could not parse api base url"))
}
sess, err := session.Must(ctn).Get(w, r)
if err != nil {
panic(errors.Wrap(err, "could not retrieve session"))
}
accessToken := sess.Get(middleware.SessionOAuth2AccessToken)
proxy := httputil.NewSingleHostReverseProxy(apiBaseURL)
2019-12-01 22:12:13 +01:00
proxy.Director = func(rr *http.Request) {
rr.Host = apiBaseURL.Host
rr.URL.Scheme = apiBaseURL.Scheme
rr.URL.Host = apiBaseURL.Host
rr.Method = r.Method
rr.Header.Add("Accept", "application/json")
rr.Header.Add("Authorization", fmt.Sprintf("token %s", accessToken))
2019-11-28 11:50:51 +01:00
}
proxy.ServeHTTP(w, r)
}