github.com/xmidt-org/webpa-common@v1.11.9/convey/conveyhttp/header.go (about)

     1  package conveyhttp
     2  
     3  import (
     4  	"errors"
     5  	"net/http"
     6  
     7  	"github.com/xmidt-org/webpa-common/convey"
     8  )
     9  
    10  // DefaultHeaderName is the HTTP header assumed to contain Convey data when no header is supplied
    11  const DefaultHeaderName = "X-Webpa-Convey"
    12  
    13  // ErrMissingHeader indicates that no HTTP header exists which contains convey information
    14  var ErrMissingHeader = errors.New("No convey header present")
    15  
    16  // HeaderTranslator is an analog to convey.Translator, except that this type works with http.Header.
    17  type HeaderTranslator interface {
    18  	// FromHeader extracts the configued header and attempts to parse it as a convey map
    19  	FromHeader(http.Header) (convey.C, error)
    20  
    21  	// ToHeader takes the given convey map, converts it to a string, and sets that string into the supplied header
    22  	ToHeader(http.Header, convey.C) error
    23  }
    24  
    25  // headerTranslator is the internal HeaderTranslator implementation
    26  type headerTranslator struct {
    27  	headerName string
    28  	translator convey.Translator
    29  }
    30  
    31  // NewHeaderTranslator creates a HeaderTranslator that uses a convey.Translator to produce
    32  // convey maps.
    33  func NewHeaderTranslator(headerName string, translator convey.Translator) HeaderTranslator {
    34  	if len(headerName) == 0 {
    35  		headerName = DefaultHeaderName
    36  	}
    37  
    38  	if translator == nil {
    39  		translator = convey.NewTranslator(nil)
    40  	}
    41  
    42  	return &headerTranslator{
    43  		headerName: headerName,
    44  		translator: translator,
    45  	}
    46  }
    47  
    48  func (ht *headerTranslator) FromHeader(h http.Header) (convey.C, error) {
    49  	v := h.Get(ht.headerName)
    50  	if len(v) == 0 {
    51  		return nil, convey.Error{ErrMissingHeader, convey.Missing}
    52  	}
    53  
    54  	return convey.ReadString(ht.translator, v)
    55  }
    56  
    57  func (ht *headerTranslator) ToHeader(h http.Header, c convey.C) error {
    58  	v, err := convey.WriteString(ht.translator, c)
    59  	if err == nil {
    60  		h.Set(ht.headerName, v)
    61  	}
    62  
    63  	return err
    64  }