github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/courier/transport_http/decode.go (about)

     1  package transport_http
     2  
     3  import (
     4  	"net/http"
     5  	"reflect"
     6  
     7  	"github.com/johnnyeven/libtools/courier/httpx"
     8  
     9  	"github.com/julienschmidt/httprouter"
    10  
    11  	"github.com/johnnyeven/libtools/courier"
    12  	"github.com/johnnyeven/libtools/courier/transport_http/transform"
    13  	"github.com/johnnyeven/libtools/reflectx"
    14  )
    15  
    16  func createHttpRequestDecoder(r *http.Request, params *httprouter.Params) courier.OperatorDecoder {
    17  	return func(op courier.IOperator, rv reflect.Value) (err error) {
    18  		if httpRequestTransformer, ok := op.(IHttpRequestTransformer); ok {
    19  			httpRequestTransformer.TransformHttpRequest(r)
    20  		}
    21  
    22  		requestID := r.Header.Get(httpx.HeaderRequestID)
    23  		if requestID != "" {
    24  			_, version, exists := courier.ParseVersionSwitch(requestID)
    25  			if exists {
    26  				r.Header.Add(courier.VersionSwitchKey, version)
    27  			}
    28  		}
    29  
    30  		return transform.MarshalParameters(transform.ParameterGroupFromReflectValue(rv), &ParameterValuesGetter{
    31  			ParameterValuesGetter: transform.NewParameterValuesGetter(r),
    32  			Params:                params,
    33  		})
    34  	}
    35  }
    36  
    37  type ParameterValuesGetter struct {
    38  	*transform.ParameterValuesGetter
    39  	Params *httprouter.Params
    40  }
    41  
    42  func (getter *ParameterValuesGetter) Param(name string) string {
    43  	return getter.Params.ByName(name)
    44  }
    45  
    46  func MarshalOperator(r *http.Request, operator courier.IOperator) (err error) {
    47  	params := httprouter.Params{}
    48  
    49  	if canPath, ok := (operator).(IPath); ok {
    50  		params, err = GetParams(canPath.Path(), r.URL.Path)
    51  	}
    52  
    53  	opDecode := createHttpRequestDecoder(r, &params)
    54  	op, err := courier.NewOperatorBy(reflectx.IndirectType(reflect.TypeOf(operator)), operator, opDecode)
    55  	if err != nil {
    56  		return err
    57  	}
    58  
    59  	reflect.Indirect(reflect.ValueOf(operator)).Set(reflect.ValueOf(op).Elem())
    60  	return nil
    61  }