Path: blob/main/components/openvsx-proxy/pkg/errorhandler.go
2498 views
// Copyright (c) 2021 Gitpod GmbH. All rights reserved.1// Licensed under the GNU Affero General Public License (AGPL).2// See License.AGPL.txt in the project root for license information.34package pkg56import (7"net/http"8"time"910"github.com/gitpod-io/gitpod/common-go/log"11"github.com/sirupsen/logrus"12)1314func (o *OpenVSXProxy) ErrorHandler(rw http.ResponseWriter, r *http.Request, e error) {15reqid := r.Context().Value(REQUEST_ID_CTX).(string)16key, ok := r.Context().Value(REQUEST_CACHE_KEY_CTX).(string)1718logFields := logrus.Fields{19LOG_FIELD_FUNC: "error_handler",20LOG_FIELD_REQUEST_ID: reqid,21LOG_FIELD_REQUEST: key,22LOG_FIELD_STATUS: "error",23}2425start := time.Now()26defer func(ts time.Time) {27duration := time.Since(ts)28o.metrics.DurationResponseProcessingHistogram.Observe(duration.Seconds())29log.30WithFields(logFields).31WithFields(o.DurationLogFields(duration)).32Info("processing error finished")33}(start)3435log.WithFields(logFields).WithError(e).Warn("handling error")36o.metrics.IncStatusCounter(r, "error")3738if !ok {39return40}4142if key == "" {43log.WithFields(logFields).Error("cache key header is missing")44rw.WriteHeader(http.StatusBadGateway)45return46}4748cached, ok, err := o.ReadCache(key)49if err != nil {50log.WithFields(logFields).WithError(err).Error("cannot read from cache")51rw.WriteHeader(http.StatusBadGateway)52return53}54if !ok {55log.WithFields(logFields).Debug("cache has no entry for key")56rw.WriteHeader(http.StatusBadGateway)57return58}59for k, v := range cached.Header {60for i, val := range v {61if i == 0 {62rw.Header().Set(k, val)63} else {64rw.Header().Add(k, val)65}66}67}68if v := rw.Header().Get("Access-Control-Allow-Origin"); v != "" && v != "*" {69rw.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))70}71rw.WriteHeader(cached.StatusCode)72rw.Write(cached.Body)73log.WithFields(logFields).Debug("used cached response due to a proxy error")74o.metrics.BackupCacheServeCounter.Inc()75}767778