• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang codec.MsgpackHandle类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/ugorji/go/codec.MsgpackHandle的典型用法代码示例。如果您正苦于以下问题:Golang MsgpackHandle类的具体用法?Golang MsgpackHandle怎么用?Golang MsgpackHandle使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了MsgpackHandle类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: NewForwardInput

func NewForwardInput(logger *logging.Logger, bind string, port Port) (*ForwardInput, error) {
	_codec := codec.MsgpackHandle{}
	_codec.MapType = reflect.TypeOf(map[string]interface{}(nil))
	_codec.RawToString = false
	addr, err := net.ResolveTCPAddr("tcp", bind)
	if err != nil {
		logger.Error("%s", err.Error())
		return nil, err
	}
	listener, err := net.ListenTCP("tcp", addr)
	if err != nil {
		logger.Error("%s", err.Error())
		return nil, err
	}
	return &ForwardInput{
		port:           port,
		logger:         logger,
		bind:           bind,
		listener:       listener,
		codec:          &_codec,
		clients:        make(map[*net.TCPConn]*forwardClient),
		clientsMtx:     sync.Mutex{},
		entries:        0,
		wg:             sync.WaitGroup{},
		acceptChan:     make(chan *net.TCPConn),
		shutdownChan:   make(chan struct{}),
		isShuttingDown: uintptr(0),
	}, nil
}
开发者ID:suzukaze,项目名称:fluentd-forwarder,代码行数:29,代码来源:input.go


示例2: scriptBody

func scriptBody(sessionId []byte, graphName, script string, bindings map[string]interface{}) (out []byte, err error) {
	var (
		mh            = new(codec.MsgpackHandle)
		enc           = codec.NewEncoderBytes(&out, mh)
		reqId         = uuid.NewV4()
		isSessionless = bytes.Equal(sessionId, sessionlessUuid[:])
	)
	mh.MapType = reflect.TypeOf(map[string]interface{}(nil))
	meta := map[string]interface{}{
		"inSession":    !isSessionless,
		"isolate":      isSessionless,
		"graphObjName": "g",
	}
	if isSessionless {
		meta["graphName"] = graphName
	}
	err = enc.Encode([]interface{}{
		sessionId,
		reqId[:],
		meta,
		"groovy",
		script,
		bindings,
	})
	return
}
开发者ID:philipsoutham,项目名称:gorexpro,代码行数:26,代码来源:rexpro.go


示例3: UnpackProxyRequest

// TBD: Extract more info
func UnpackProxyRequest(raw []byte) (*http.Request, error) {
	var (
		mh codec.MsgpackHandle
		h  = &mh
	)
	var v []interface{}
	mh.SliceType = reflect.TypeOf(Headers(nil))
	codec.NewDecoderBytes(raw, h).Decode(&v)
	r, err := http.NewRequest(string(v[0].([]uint8)), string(v[1].([]uint8)), bytes.NewBuffer(v[4].([]byte)))
	if err != nil {
		return nil, err
	}
	r.Header = CocaineHeaderToHttpHeader(v[3].(Headers))

	r.Host = r.Header.Get("Host")

	if xRealIp := r.Header.Get("X-Real-IP"); xRealIp != "" {
		r.RemoteAddr = xRealIp
	}

	err = decompressBody(r)
	if err != nil {
		return nil, err
	}

	return r, nil
}
开发者ID:ascheglov,项目名称:cocaine-framework-go,代码行数:28,代码来源:httpreq.go


示例4: TestSpanMsgPack

func TestSpanMsgPack(t *testing.T) {
	span := Span{Id: TestId("33f25a1a750a471db5bafa59309d7d6f"),
		SpanData: SpanData{
			Begin:       1234,
			End:         5678,
			Description: "getFileDescriptors",
			Parents:     []SpanId{},
			TracerId:    "testTracerId",
		}}
	mh := new(codec.MsgpackHandle)
	mh.WriteExt = true
	w := bytes.NewBuffer(make([]byte, 0, 2048))
	enc := codec.NewEncoder(w, mh)
	err := enc.Encode(span)
	if err != nil {
		t.Fatal("Error encoding span as msgpack: " + err.Error())
	}
	buf := w.Bytes()
	fmt.Printf("span: %s\n", hex.EncodeToString(buf))
	mh = new(codec.MsgpackHandle)
	mh.WriteExt = true
	dec := codec.NewDecoder(bytes.NewReader(buf), mh)
	var span2 Span
	err = dec.Decode(&span2)
	if err != nil {
		t.Fatal("Failed to reverse msgpack encoding for " + span.String())
	}
	ExpectSpansEqual(t, &span, &span2)
}
开发者ID:gauravrmazra,项目名称:incubator-htrace,代码行数:29,代码来源:span_test.go


示例5: DecodeRequest

func DecodeRequest(body []byte, req *Request) (err error) {
	mh := codec.MsgpackHandle{RawToString: true}
	mh.MapType = reflect.TypeOf(map[string]interface{}(nil))
	dec := codec.NewDecoderBytes(body, &mh)
	err = dec.Decode(req)
	return
}
开发者ID:groovenauts,项目名称:magellan-proxy,代码行数:7,代码来源:message.go


示例6: decodeBody

func decodeBody(body []byte) (retVal []interface{}, err error) {
	var mh = new(codec.MsgpackHandle)
	mh.MapType = reflect.TypeOf(map[string]interface{}(nil))
	dec := codec.NewDecoderBytes(body, mh)
	if e := dec.Decode(&retVal); e != nil {
		err = errors.New("rexpro: msgpack decode error")
	}
	return
}
开发者ID:philipsoutham,项目名称:gorexpro,代码行数:9,代码来源:rexpro.go


示例7: ParseRequest

func (gofetcher *Gofetcher) ParseRequest(method string, requestBody []byte) (request *Request) {
	var (
		mh              codec.MsgpackHandle
		h                     = &mh
		timeout         int64 = DefaultTimeout
		cookies         Cookies
		headers              = make(http.Header)
		followRedirects bool = DefaultFollowRedirects
		body            *bytes.Buffer
	)
	mh.MapType = reflect.TypeOf(map[string]interface{}(nil))
	var res []interface{}
	codec.NewDecoderBytes(requestBody, h).Decode(&res)
	url := string(res[0].([]uint8))
	switch {
	case method == "GET" || method == "HEAD" || method == "DELETE":
		if len(res) > 1 {
			timeout = parseTimeout(res[1])
		}
		if len(res) > 2 {
			cookies = parseCookies(res[2].(map[string]interface{}))
		}
		if len(res) > 3 {
			headers = parseHeaders(res[3].(map[string]interface{}))
		}
		if len(res) > 4 {
			followRedirects = res[4].(bool)
		}
	case method == "POST" || method == "PUT" || method == "PATCH":
		if len(res) > 1 {
			body = bytes.NewBuffer(res[1].([]byte))
		}
		if len(res) > 2 {
			timeout = parseTimeout(res[2])
		}
		if len(res) > 3 {
			cookies = parseCookies(res[3].(map[string]interface{}))
		}
		if len(res) > 4 {
			headers = parseHeaders(res[4].(map[string]interface{}))
		}
		if len(res) > 5 {
			followRedirects = res[5].(bool)
		}
	}

	request = &Request{Method: method, URL: url, Timeout: timeout,
		FollowRedirects: followRedirects,
		Cookies:         cookies, Headers: headers}
	if body != nil {
		request.Body = body
	}
	return request
}
开发者ID:sguzwf,项目名称:cocaine-gofetcher,代码行数:54,代码来源:gofetcher.go


示例8: ReadResponseBody

func (cdc *HrpcClientCodec) ReadResponseBody(body interface{}) error {
	mh := new(codec.MsgpackHandle)
	mh.WriteExt = true
	dec := codec.NewDecoder(io.LimitReader(cdc.rwc, int64(cdc.length)), mh)
	err := dec.Decode(body)
	if err != nil {
		return errors.New(fmt.Sprintf("Failed to read response body: %s",
			err.Error()))
	}
	return nil
}
开发者ID:clehene,项目名称:incubator-htrace,代码行数:11,代码来源:hclient.go


示例9: WriteResponse

func (cdc *HrpcServerCodec) WriteResponse(resp *rpc.Response, msg interface{}) error {
	var err error
	buf := EMPTY
	if msg != nil {
		mh := new(codec.MsgpackHandle)
		mh.WriteExt = true
		w := bytes.NewBuffer(make([]byte, 0, 128))
		enc := codec.NewEncoder(w, mh)
		err := enc.Encode(msg)
		if err != nil {
			return createErrAndWarn(cdc.lg, fmt.Sprintf("Failed to marshal "+
				"response message: %s", err.Error()))
		}
		buf = w.Bytes()
	}
	hdr := common.HrpcResponseHeader{}
	hdr.MethodId = common.HrpcMethodNameToId(resp.ServiceMethod)
	hdr.Seq = resp.Seq
	hdr.ErrLength = uint32(len(resp.Error))
	hdr.Length = uint32(len(buf))
	writer := bufio.NewWriterSize(cdc.conn, 256)
	err = binary.Write(writer, binary.LittleEndian, &hdr)
	if err != nil {
		return createErrAndWarn(cdc.lg, fmt.Sprintf("Failed to write response "+
			"header: %s", err.Error()))
	}
	if hdr.ErrLength > 0 {
		_, err = io.WriteString(writer, resp.Error)
		if err != nil {
			return createErrAndWarn(cdc.lg, fmt.Sprintf("Failed to write error "+
				"string: %s", err.Error()))
		}
	}
	if hdr.Length > 0 {
		var length int
		length, err = writer.Write(buf)
		if err != nil {
			return createErrAndWarn(cdc.lg, fmt.Sprintf("Failed to write response "+
				"message: %s", err.Error()))
		}
		if uint32(length) != hdr.Length {
			return createErrAndWarn(cdc.lg, fmt.Sprintf("Failed to write all of "+
				"response message: %s", err.Error()))
		}
	}
	err = writer.Flush()
	if err != nil {
		return createErrAndWarn(cdc.lg, fmt.Sprintf("Failed to write the response "+
			"bytes: %s", err.Error()))
	}
	return nil
}
开发者ID:clehene,项目名称:incubator-htrace,代码行数:52,代码来源:hrpc.go


示例10: WriteFile

func WriteFile(path string, obj interface{}) (err error) {
	mh := codec.MsgpackHandle{}
	mh.AsSymbols = codec.AsSymbolNone
	mh.RawToString = true
	buf := &bytes.Buffer{}
	encoder := codec.NewEncoder(buf, &mh)
	err = encoder.Encode(obj)
	if err != nil {
		return
	}
	err = ioutil.WriteFile(path, buf.Bytes(), os.FileMode(0777))
	return
}
开发者ID:iizotop,项目名称:kmg,代码行数:13,代码来源:kmgMsgPack.go


示例11: decodeSpan

func (shd *shard) decodeSpan(sid common.SpanId, buf []byte) (*common.Span, error) {
	r := bytes.NewBuffer(buf)
	mh := new(codec.MsgpackHandle)
	mh.WriteExt = true
	decoder := codec.NewDecoder(r, mh)
	data := common.SpanData{}
	err := decoder.Decode(&data)
	if err != nil {
		return nil, err
	}
	if data.Parents == nil {
		data.Parents = []common.SpanId{}
	}
	return &common.Span{Id: common.SpanId(sid), SpanData: data}, nil
}
开发者ID:gauravrmazra,项目名称:incubator-htrace,代码行数:15,代码来源:datastore.go


示例12: writeShardInfo

func (shd *ShardLoader) writeShardInfo(info *ShardInfo) error {
	mh := new(codec.MsgpackHandle)
	mh.WriteExt = true
	w := new(bytes.Buffer)
	enc := codec.NewEncoder(w, mh)
	err := enc.Encode(info)
	if err != nil {
		return errors.New(fmt.Sprintf("msgpack encoding error: %s",
			err.Error()))
	}
	err = shd.ldb.Put(shd.dld.writeOpts, []byte{SHARD_INFO_KEY}, w.Bytes())
	if err != nil {
		return errors.New(fmt.Sprintf("leveldb write error: %s",
			err.Error()))
	}
	return nil
}
开发者ID:gauravrmazra,项目名称:incubator-htrace,代码行数:17,代码来源:loader.go


示例13: UnpackProxyRequest

// TBD: Extract more info
func UnpackProxyRequest(raw []byte) *http.Request {
	var (
		mh codec.MsgpackHandle
		h  = &mh
	)
	var v []interface{}
	mh.SliceType = reflect.TypeOf(Headers(nil))
	codec.NewDecoderBytes(raw, h).Decode(&v)
	r, err := http.NewRequest(string(v[0].([]uint8)), string(v[1].([]uint8)), bytes.NewBuffer(v[4].([]byte)))
	if err != nil {
		fmt.Println("Error", err)
	}
	r.Header = CocaineHeaderToHttpHeader(v[3].(Headers))
	if xRealIp := r.Header.Get("X-Real-IP"); xRealIp != "" {
		r.RemoteAddr = xRealIp
	}
	return r
}
开发者ID:kod3r,项目名称:cocaine-framework-go,代码行数:19,代码来源:httpreq.go


示例14: ReadRequestBody

func (cdc *HrpcServerCodec) ReadRequestBody(body interface{}) error {
	if cdc.lg.TraceEnabled() {
		cdc.lg.Tracef("Reading HRPC %d-byte request body from %s\n",
			cdc.length, cdc.conn.RemoteAddr())
	}
	mh := new(codec.MsgpackHandle)
	mh.WriteExt = true
	dec := codec.NewDecoder(io.LimitReader(cdc.conn, int64(cdc.length)), mh)
	err := dec.Decode(body)
	if err != nil {
		return createErrAndWarn(cdc.lg, fmt.Sprintf("Failed to read request "+
			"body from %s: %s", cdc.conn.RemoteAddr(), err.Error()))
	}
	if cdc.lg.TraceEnabled() {
		cdc.lg.Tracef("Read body from %s: %s\n",
			cdc.conn.RemoteAddr(), asJson(&body))
	}
	return nil
}
开发者ID:clehene,项目名称:incubator-htrace,代码行数:19,代码来源:hrpc.go


示例15: sessionBody

func (s *session) sessionBody(kill bool) (out []byte, err error) {
	var (
		mh    = new(codec.MsgpackHandle)
		enc   = codec.NewEncoderBytes(&out, mh)
		reqId = uuid.NewV4()
	)
	mh.MapType = reflect.TypeOf(map[string]interface{}(nil))
	err = enc.Encode([]interface{}{
		s.sId,
		reqId[:],
		map[string]interface{}{
			"graphName":    s.r.graphName,
			"graphObjName": "g",
			"killSession":  kill,
		},
		s.username,
		s.password,
	})
	return
}
开发者ID:philipsoutham,项目名称:gorexpro,代码行数:20,代码来源:rexpro.go


示例16: newForwardInput

func newForwardInput(factory *ForwardInputFactory, logger *log.Logger, bind string, port ik.Port) (*ForwardInput, error) {
	_codec := codec.MsgpackHandle{}
	_codec.MapType = reflect.TypeOf(map[string]interface{}(nil))
	_codec.RawToString = false
	listener, err := net.Listen("tcp", bind)
	if err != nil {
		logger.Fatal(err.Error())
		return nil, err
	}
	return &ForwardInput{
		factory:  factory,
		port:     port,
		logger:   logger,
		bind:     bind,
		listener: listener,
		codec:    &_codec,
		running:  false,
		clients:  make(map[net.Conn]*forwardClient),
	}, nil
}
开发者ID:kiyoto,项目名称:ik,代码行数:20,代码来源:forward.go


示例17: WriteRequest

func (cdc *HrpcClientCodec) WriteRequest(req *rpc.Request, msg interface{}) error {
	methodId := common.HrpcMethodNameToId(req.ServiceMethod)
	if methodId == common.METHOD_ID_NONE {
		return errors.New(fmt.Sprintf("HrpcClientCodec: Unknown method name %s",
			req.ServiceMethod))
	}
	mh := new(codec.MsgpackHandle)
	mh.WriteExt = true
	w := bytes.NewBuffer(make([]byte, 0, 2048))
	enc := codec.NewEncoder(w, mh)
	err := enc.Encode(msg)
	if err != nil {
		return errors.New(fmt.Sprintf("HrpcClientCodec: Unable to marshal "+
			"message as msgpack: %s", err.Error()))
	}
	buf := w.Bytes()
	if len(buf) > common.MAX_HRPC_BODY_LENGTH {
		return errors.New(fmt.Sprintf("HrpcClientCodec: message body is %d "+
			"bytes, but the maximum message size is %d bytes.",
			len(buf), common.MAX_HRPC_BODY_LENGTH))
	}
	hdr := common.HrpcRequestHeader{
		Magic:    common.HRPC_MAGIC,
		MethodId: methodId,
		Seq:      req.Seq,
		Length:   uint32(len(buf)),
	}
	err = binary.Write(cdc.rwc, binary.LittleEndian, &hdr)
	if err != nil {
		return errors.New(fmt.Sprintf("Error writing header bytes: %s",
			err.Error()))
	}
	_, err = cdc.rwc.Write(buf)
	if err != nil {
		return errors.New(fmt.Sprintf("Error writing body bytes: %s",
			err.Error()))
	}
	return nil
}
开发者ID:clehene,项目名称:incubator-htrace,代码行数:39,代码来源:hclient.go


示例18: NewForwardOutput

func NewForwardOutput(logger *logging.Logger, bind string, retryInterval time.Duration, connectionTimeout time.Duration, writeTimeout time.Duration, flushInterval time.Duration, journalGroupPath string, maxJournalChunkSize int64, metadata string) (*ForwardOutput, error) {
	_codec := codec.MsgpackHandle{}
	_codec.MapType = reflect.TypeOf(map[string]interface{}(nil))
	_codec.RawToString = false
	_codec.StructToArray = true

	journalFactory := NewFileJournalGroupFactory(
		logger,
		randSource,
		time.Now,
		".log",
		os.FileMode(0600),
		maxJournalChunkSize,
	)
	output := &ForwardOutput{
		logger:               logger,
		codec:                &_codec,
		bind:                 bind,
		retryInterval:        retryInterval,
		connectionTimeout:    connectionTimeout,
		writeTimeout:         writeTimeout,
		wg:                   sync.WaitGroup{},
		flushInterval:        flushInterval,
		emitterChan:          make(chan FluentRecordSet),
		spoolerShutdownChan:  make(chan struct{}),
		isShuttingDown:       0,
		completion:           sync.Cond{L: &sync.Mutex{}},
		hasShutdownCompleted: false,
		metadata:             metadata,
	}
	journalGroup, err := journalFactory.GetJournalGroup(journalGroupPath, output)
	if err != nil {
		return nil, err
	}
	output.journalGroup = journalGroup
	output.journal = journalGroup.GetJournal("output")
	return output, nil
}
开发者ID:idahoakl,项目名称:fluentd-forwarder,代码行数:38,代码来源:output.go


示例19: unpackchunk

func (locator *Locator) unpackchunk(chunk RawMessage) ResolveResult {
	defer func() {
		if err := recover(); err != nil {
			log.Println("defer", err)
		}
	}()
	var v []interface{}
	var MH codec.MsgpackHandle
	MH.MapType = reflect.TypeOf(map[int]string(nil))
	err := codec.NewDecoderBytes(chunk, &MH).Decode(&v)
	if err != nil {
		log.Println("unpack chunk error", err)
	}
	if len(v) == 3 {
		v_endpoint := v[0].([]interface{})
		endpoint := Endpoint{string(v_endpoint[0].([]uint8)), v_endpoint[1].(uint64)}
		version := v[1].(int64)
		api := v[2].(map[int]string)
		return ResolveResult{true, endpoint, version, api}
	} else {
		panic("Bad format")
	}
}
开发者ID:kod3r,项目名称:cocaine-framework-go,代码行数:23,代码来源:locator.go


示例20: readShardInfo

func (shd *ShardLoader) readShardInfo() (*ShardInfo, error) {
	buf, err := shd.ldb.Get(shd.dld.readOpts, []byte{SHARD_INFO_KEY})
	if err != nil {
		return nil, errors.New(fmt.Sprintf("readShardInfo(%s): failed to "+
			"read shard info key: %s", shd.path, err.Error()))
	}
	if len(buf) == 0 {
		return nil, errors.New(fmt.Sprintf("readShardInfo(%s): got zero-"+
			"length value for shard info key.", shd.path))
	}
	mh := new(codec.MsgpackHandle)
	mh.WriteExt = true
	r := bytes.NewBuffer(buf)
	decoder := codec.NewDecoder(r, mh)
	shardInfo := &ShardInfo{
		LayoutVersion: UNKNOWN_LAYOUT_VERSION,
	}
	err = decoder.Decode(shardInfo)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("readShardInfo(%s): msgpack "+
			"decoding failed for shard info key: %s", shd.path, err.Error()))
	}
	return shardInfo, nil
}
开发者ID:gauravrmazra,项目名称:incubator-htrace,代码行数:24,代码来源:loader.go



注:本文中的github.com/ugorji/go/codec.MsgpackHandle类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang core.Message类代码示例发布时间:2022-05-28
下一篇:
Golang codec.Encoder类代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap