github.com/erda-project/erda-infra@v1.0.9/providers/httpserver/interceptors/interceptor.go (about)

     1  // Copyright (c) 2021 Terminus, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package interceptors
    16  
    17  import (
    18  	"strconv"
    19  
    20  	"github.com/labstack/echo"
    21  
    22  	"github.com/erda-project/erda-infra/base/logs"
    23  )
    24  
    25  const (
    26  	defaultDebugFlag = "__debug__"
    27  )
    28  
    29  // Option .
    30  type Option struct {
    31  	EnableFetchFuncs []EnableFetchFunc
    32  	Log              logs.Logger
    33  }
    34  
    35  // NewOption .
    36  func NewOption(funcs []EnableFetchFunc, log logs.Logger) Option {
    37  	return Option{
    38  		EnableFetchFuncs: funcs,
    39  		Log:              log,
    40  	}
    41  }
    42  
    43  // EnableFetchFunc is a func used by middleware invoker to define how to get enable switch.
    44  type EnableFetchFunc func(c echo.Context) bool
    45  
    46  var defaultEnableFetchFunc EnableFetchFunc = func(c echo.Context) bool {
    47  	if c.Request().URL.Query().Has(defaultDebugFlag) {
    48  		return true
    49  	}
    50  	if _, ok := c.Request().Header[defaultDebugFlag]; ok {
    51  		return true
    52  	}
    53  	return false
    54  }
    55  
    56  // judgeAnyEnable judge enable if any func executed return true
    57  func judgeAnyEnable(c echo.Context, enableFetchFuncs []EnableFetchFunc) bool {
    58  	for _, f := range enableFetchFuncs {
    59  		if f(c) {
    60  			return true
    61  		}
    62  	}
    63  	return defaultEnableFetchFunc(c)
    64  }
    65  
    66  // PassThroughDebugFlag is the middleware to pass through the debug flag.
    67  func PassThroughDebugFlag() echo.MiddlewareFunc {
    68  	return func(next echo.HandlerFunc) echo.HandlerFunc {
    69  		return func(c echo.Context) error {
    70  			if defaultEnableFetchFunc(c) {
    71  				c.Response().Header().Set(defaultDebugFlag, strconv.FormatBool(true))
    72  			}
    73  			return next(c)
    74  		}
    75  	}
    76  }