github.com/cs3org/reva/v2@v2.27.7/internal/http/interceptors/appctx/appctx.go (about)

     1  // Copyright 2018-2021 CERN
     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  // In applying this license, CERN does not waive the privileges and immunities
    16  // granted to it by virtue of its status as an Intergovernmental Organization
    17  // or submit itself to any jurisdiction.
    18  
    19  // Package appctx creates a context with useful
    20  // components attached to the context like loggers and
    21  // token managers.
    22  package appctx
    23  
    24  import (
    25  	"net/http"
    26  
    27  	"github.com/cs3org/reva/v2/pkg/appctx"
    28  	"github.com/rs/zerolog"
    29  	"go.opentelemetry.io/otel/trace"
    30  )
    31  
    32  // name is the Tracer name used to identify this instrumentation library.
    33  const tracerName = "appctx"
    34  
    35  // New returns a new HTTP middleware that stores the log
    36  // in the context with request ID information.
    37  func New(log zerolog.Logger, tp trace.TracerProvider) func(http.Handler) http.Handler {
    38  	chain := func(h http.Handler) http.Handler {
    39  		return handler(log, tp, h)
    40  	}
    41  	return chain
    42  }
    43  
    44  func handler(log zerolog.Logger, tp trace.TracerProvider, h http.Handler) http.Handler {
    45  
    46  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    47  		ctx := r.Context()
    48  		span := trace.SpanFromContext(ctx)
    49  		defer span.End()
    50  		if !span.SpanContext().HasTraceID() {
    51  			ctx, span = tp.Tracer(tracerName).Start(ctx, "http interceptor")
    52  		}
    53  
    54  		sub := log.With().Str("traceid", span.SpanContext().TraceID().String()).Logger()
    55  		ctx = appctx.WithLogger(ctx, &sub)
    56  		ctx = appctx.WithTracerProvider(ctx, tp)
    57  		r = r.WithContext(ctx)
    58  		h.ServeHTTP(w, r)
    59  	})
    60  }