github.com/mendersoftware/go-lib-micro@v0.0.0-20240304135804-e8e39c59b148/requestid/utils.go (about)

     1  // Copyright 2023 Northern.tech AS
     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  package requestid
    15  
    16  import (
    17  	"context"
    18  
    19  	"github.com/ant0ine/go-json-rest/rest"
    20  )
    21  
    22  type requestIdKeyType int
    23  
    24  const (
    25  	requestIdKey requestIdKeyType = 0
    26  )
    27  
    28  // GetReqId helper for retrieving current request Id
    29  func GetReqId(r *rest.Request) string {
    30  	return FromContext(r.Context())
    31  }
    32  
    33  // SetReqId is a helper for setting request ID in request context
    34  func SetReqId(r *rest.Request, reqid string) *rest.Request {
    35  	ctx := WithContext(r.Context(), reqid)
    36  	r.Request = r.Request.WithContext(ctx)
    37  	return r
    38  }
    39  
    40  // FromContext extracts current request Id from context.Context
    41  func FromContext(ctx context.Context) string {
    42  	val := ctx.Value(requestIdKey)
    43  	if v, ok := val.(string); ok {
    44  		return v
    45  	}
    46  	return ""
    47  }
    48  
    49  // WithContext adds request to context `ctx` and returns the resulting context.
    50  func WithContext(ctx context.Context, reqid string) context.Context {
    51  	return context.WithValue(ctx, requestIdKey, reqid)
    52  }