github.com/xmidt-org/webpa-common@v1.11.9/service/servicehttp/decoders.go (about)

     1  package servicehttp
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net/http"
     7  
     8  	gokithttp "github.com/go-kit/kit/transport/http"
     9  	"github.com/gorilla/mux"
    10  	"github.com/xmidt-org/webpa-common/service"
    11  	"github.com/xmidt-org/webpa-common/xhttp"
    12  )
    13  
    14  // KeyFromHeader produces a go-kit decoder which expects an HTTP header to contain the service key.
    15  func KeyFromHeader(header string, parser service.KeyParser) gokithttp.DecodeRequestFunc {
    16  	if len(header) == 0 {
    17  		panic("A header is required")
    18  	}
    19  
    20  	if parser == nil {
    21  		panic("A parser is required")
    22  	}
    23  
    24  	missingHeader := &xhttp.Error{
    25  		Code: http.StatusBadRequest,
    26  		Text: fmt.Sprintf("missing %s header", header),
    27  	}
    28  
    29  	return func(_ context.Context, r *http.Request) (interface{}, error) {
    30  		v := r.Header.Get(header)
    31  		if len(v) == 0 {
    32  			return nil, missingHeader
    33  		}
    34  
    35  		return parser(v)
    36  	}
    37  }
    38  
    39  // KeyFromPath uses a gorilla/mux path variable as the source for the service Key.
    40  func KeyFromPath(variable string, parser service.KeyParser) gokithttp.DecodeRequestFunc {
    41  	if len(variable) == 0 {
    42  		panic("A variable is required")
    43  	}
    44  
    45  	if parser == nil {
    46  		panic("A parser is required")
    47  	}
    48  
    49  	noPathVariables := &xhttp.Error{
    50  		Code: http.StatusInternalServerError,
    51  		Text: "no path variables found",
    52  	}
    53  
    54  	missingValue := &xhttp.Error{
    55  		Code: http.StatusBadRequest,
    56  		Text: fmt.Sprintf("missing path variable %s", variable),
    57  	}
    58  
    59  	return func(_ context.Context, r *http.Request) (interface{}, error) {
    60  		vars := mux.Vars(r)
    61  		if len(vars) == 0 {
    62  			return nil, noPathVariables
    63  		}
    64  
    65  		v, ok := vars[variable]
    66  		if !ok {
    67  			return nil, missingValue
    68  		}
    69  
    70  		return parser(v)
    71  	}
    72  }