示例#1
0
func TestAPITopologyHosts(t *testing.T) {
	ts := topologyServer()
	defer ts.Close()
	is404(t, ts, "/api/topology/hosts/foobar")
	{
		body := getRawJSON(t, ts, "/api/topology/hosts")
		var topo app.APITopology
		decoder := codec.NewDecoderBytes(body, &codec.JsonHandle{})
		if err := decoder.Decode(&topo); err != nil {
			t.Fatal(err)
		}

		// Should have the rendered host nodes
		for id := range expected.RenderedHosts {
			if _, ok := topo.Nodes[id]; !ok {
				t.Errorf("Expected output to include node: %s, but wasn't found", id)
			}
		}
	}
	{
		body := getRawJSON(t, ts, "/api/topology/hosts/"+fixture.ServerHostNodeID)
		var node app.APINode
		decoder := codec.NewDecoderBytes(body, &codec.JsonHandle{})
		if err := decoder.Decode(&node); err != nil {
			t.Fatal(err)
		}
		equals(t, fixture.ServerHostNodeID, node.Node.ID)
		equals(t, "server", node.Node.Label)
		equals(t, false, node.Node.Pseudo)
		// Let's not unit-test the specific content of the detail tables
	}
}
// Decode decodes msgpack representation into Snapshot
func (s *Snapshot) Decode(input []byte) error {
	decoder := codec.NewDecoderBytes(input, &codec.MsgpackHandle{})
	err := decoder.Decode(s)
	if err != nil {
		if strings.HasPrefix(err.Error(), "codec.decoder: readContainerLen: Unrecognized descriptor byte: hex: 80") {
			// probably it is broken DB from go < 1.2, try decoding w/o time.Time
			var snapshot11 struct {
				UUID      string
				Name      string
				CreatedAt []byte

				SourceKind  string
				SourceIDs   []string
				Description string
			}

			decoder = codec.NewDecoderBytes(input, &codec.MsgpackHandle{})
			err2 := decoder.Decode(&snapshot11)
			if err2 != nil {
				return err
			}

			s.UUID = snapshot11.UUID
			s.Name = snapshot11.Name
			s.SourceKind = snapshot11.SourceKind
			s.SourceIDs = snapshot11.SourceIDs
			s.Description = snapshot11.Description
		} else {
			return err
		}
	}
	return nil
}
示例#3
0
func TestAPITopologyProcesses(t *testing.T) {
	ts := topologyServer()
	defer ts.Close()
	is404(t, ts, "/api/topology/processes/foobar")
	{
		body := getRawJSON(t, ts, "/api/topology/processes/"+fixture.ServerProcessNodeID)
		var node app.APINode
		decoder := codec.NewDecoderBytes(body, &codec.JsonHandle{})
		if err := decoder.Decode(&node); err != nil {
			t.Fatal(err)
		}
		equals(t, fixture.ServerProcessNodeID, node.Node.ID)
		equals(t, "apache", node.Node.Label)
		equals(t, false, node.Node.Pseudo)
		// Let's not unit-test the specific content of the detail tables
	}

	{
		body := getRawJSON(t, ts, "/api/topology/processes-by-name/"+
			url.QueryEscape(fixture.Client1Name))
		var node app.APINode
		decoder := codec.NewDecoderBytes(body, &codec.JsonHandle{})
		if err := decoder.Decode(&node); err != nil {
			t.Fatal(err)
		}
		equals(t, fixture.Client1Name, node.Node.ID)
		equals(t, fixture.Client1Name, node.Node.Label)
		equals(t, false, node.Node.Pseudo)
		// Let's not unit-test the specific content of the detail tables
	}
}
func TestSaltpackEncryptHideRecipients(t *testing.T) {
	tc := SetupEngineTest(t, "SaltpackEncrypt")
	defer tc.Cleanup()

	u1 := CreateAndSignupFakeUser(tc, "nalcp")
	u2 := CreateAndSignupFakeUser(tc, "nalcp")
	u3 := CreateAndSignupFakeUser(tc, "nalcp")

	trackUI := &FakeIdentifyUI{
		Proofs: make(map[string]string),
	}
	ctx := &Context{IdentifyUI: trackUI, SecretUI: u3.NewSecretUI()}

	run := func(Recips []string) {
		sink := libkb.NewBufferCloser()
		arg := &SaltpackEncryptArg{
			Opts: keybase1.SaltpackEncryptOptions{
				Recipients:     Recips,
				HideRecipients: true,
				Binary:         true,
			},
			Source: strings.NewReader("id2 and encrypt, id2 and encrypt"),
			Sink:   sink,
		}

		eng := NewSaltpackEncrypt(arg, tc.G)
		if err := RunEngine(eng, ctx); err != nil {
			t.Fatal(err)
		}

		out := sink.Bytes()
		if len(out) == 0 {
			t.Fatal("no output")
		}

		var header saltpack.EncryptionHeader
		dec := codec.NewDecoderBytes(out, &codec.MsgpackHandle{WriteExt: true})
		var b []byte
		if err := dec.Decode(&b); err != nil {
			t.Fatal(err)
		}
		dec = codec.NewDecoderBytes(b, &codec.MsgpackHandle{WriteExt: true})
		if err := dec.Decode(&header); err != nil {
			t.Fatal(err)
		}

		for _, receiver := range header.Receivers {
			if receiver.ReceiverKID != nil {
				t.Fatal("receiver KID included in anonymous saltpack header")
			}
		}

	}
	run([]string{u1.Username, u2.Username})

	// If we add ourselves, we should be smart and not error out
	// (We are u3 in this case)
	run([]string{u1.Username, u2.Username, u3.Username})
}
示例#5
0
func TestAPITopologyAddsKubernetes(t *testing.T) {
	router := mux.NewRouter()
	c := app.NewCollector(1 * time.Minute)
	app.RegisterReportPostHandler(c, router)
	app.RegisterTopologyRoutes(router, c)
	ts := httptest.NewServer(router)
	defer ts.Close()

	body := getRawJSON(t, ts, "/api/topology")

	var topologies []app.APITopologyDesc
	decoder := codec.NewDecoderBytes(body, &codec.JsonHandle{})
	if err := decoder.Decode(&topologies); err != nil {
		t.Fatalf("JSON parse error: %s", err)
	}
	equals(t, 4, len(topologies))

	// Enable the kubernetes topologies
	rpt := report.MakeReport()
	rpt.Pod = report.MakeTopology()
	rpt.Pod.Nodes[fixture.ClientPodNodeID] = kubernetes.NewPod(&api.Pod{
		ObjectMeta: api.ObjectMeta{
			Name:      "pong-a",
			Namespace: "ping",
			Labels:    map[string]string{"ponger": "true"},
		},
		Status: api.PodStatus{
			HostIP: "1.2.3.4",
			ContainerStatuses: []api.ContainerStatus{
				{ContainerID: "container1"},
				{ContainerID: "container2"},
			},
		},
	}).GetNode("")
	buf := &bytes.Buffer{}
	encoder := codec.NewEncoder(buf, &codec.MsgpackHandle{})
	if err := encoder.Encode(rpt); err != nil {
		t.Fatalf("GOB encoding error: %s", err)
	}
	checkRequest(t, ts, "POST", "/api/report", buf.Bytes())

	body = getRawJSON(t, ts, "/api/topology")
	decoder = codec.NewDecoderBytes(body, &codec.JsonHandle{})
	if err := decoder.Decode(&topologies); err != nil {
		t.Fatalf("JSON parse error: %s", err)
	}
	equals(t, 4, len(topologies))

	found := false
	for _, topology := range topologies {
		if topology.Name == "Pods" {
			found = true
			break
		}
	}
	if !found {
		t.Error("Could not find pods topology")
	}
}
示例#6
0
// ByKey find package in DB by its key
func (collection *PackageCollection) ByKey(key []byte) (*Package, error) {
	encoded, err := collection.db.Get(key)
	if err != nil {
		return nil, err
	}

	p := &Package{}

	if len(encoded) > 2 && (encoded[0] != 0xc1 || encoded[1] != 0x1) {
		oldp := &oldPackage{}

		decoder := codec.NewDecoderBytes(encoded, collection.codecHandle)
		err = decoder.Decode(oldp)
		if err != nil {
			return nil, err
		}

		p.Name = oldp.Name
		p.Version = oldp.Version
		p.Architecture = oldp.Architecture
		p.IsSource = oldp.IsSource
		p.SourceArchitecture = oldp.SourceArchitecture
		p.Source = oldp.Source
		p.Provides = oldp.Provides

		p.deps = &PackageDependencies{
			Depends:           oldp.Depends,
			BuildDepends:      oldp.BuildDepends,
			BuildDependsInDep: oldp.BuildDependsInDep,
			PreDepends:        oldp.PreDepends,
			Suggests:          oldp.Suggests,
			Recommends:        oldp.Recommends,
		}

		p.extra = &oldp.Extra
		for i := range oldp.Files {
			oldp.Files[i].Filename = filepath.Base(oldp.Files[i].Filename)
		}
		p.UpdateFiles(PackageFiles(oldp.Files))

		// Save in new format
		err = collection.Update(p)
		if err != nil {
			return nil, err
		}
	} else {
		decoder := codec.NewDecoderBytes(encoded[2:], collection.codecHandle)
		err = decoder.Decode(p)
		if err != nil {
			return nil, err
		}
	}

	p.collection = collection

	return p, nil
}
示例#7
0
func parseIncomingMessage(msg *bw.SimpleMessage, h codec.Handle) (string, ChairMessage, error) {
	var end int = strings.LastIndex(msg.URI, CHAIREND)
	var start int = strings.Index(msg.URI, CHAIRSTART) + len(CHAIRSTART)
	if end == -1 || start == -1 {
		return "", nil, errors.New(fmt.Sprintf("invalid path %v", msg.URI))
	}
	var chairid string = msg.URI[start:end]

	var contents []byte = msg.POs[0].GetContents()
	var dec *codec.Decoder = codec.NewDecoderBytes(contents, h)

	var cm ChairMessage
	var err error
	cm, err = NewChairMessageFrom(dec)
	if err != nil {
		return chairid, cm, errors.New(fmt.Sprintf("could not parse message: %v", err))
	}

	err = cm.SanityCheck()
	if err != nil {
		return chairid, cm, errors.New(fmt.Sprintf("decoded message fails sanity check: %v", err))
	} else {
		return chairid, cm, nil
	}
}
示例#8
0
func (client *Client) readMessage() (typ MsgType, session [16]byte, seq uint64, meta MetaMap, args []interface{}, err error) {
	h := &MsgHeader{}
	if err = binary.Read(client.rbuf, binary.BigEndian, h); err != nil {
		return
	}
	if h.Version != 0 {
		err = ErrUnknownVersion
		return
	}
	typ = h.Type
	bodybuf := make([]byte, h.BodySize)
	if _, err = io.ReadFull(client.rbuf, bodybuf); err != nil {
		return
	}
	var body []interface{}
	dec := codec.NewDecoderBytes(bodybuf, &mh)
	if err = dec.Decode(&body); err != nil {
		return
	}
	defer func() {
		if e := recover(); e != nil {
			switch e.(type) {
			case error:
				err = e.(error)
			default:
				err = errors.New("unexpected type during decoding")
			}
		}
	}()
	copy(session[:], []byte(body[0].(string)))
	seq = binary.BigEndian.Uint64(([]byte(body[1].(string)))[8:])
	meta = body[2].(map[string]interface{})
	args = body[3:]
	return
}
func TestMessageUnpackErrorMsg(t *testing.T) {
	const (
		session      = 1
		_type        = 5
		errorCode    = 1
		errorMessage = "someerror"
	)
	// msgpack.packb([5, 1, [1, "someerror"]])
	payload := []byte{147, 5, 1, 146, 1, 169, 115, 111, 109, 101, 101, 114, 114, 111, 114}
	var result []interface{}

	assert.NoError(t, codec.NewDecoderBytes(payload, h).Decode(&result))

	msg, err := unpackMessage(result)
	assert.NoError(t, err)

	assert.Equal(t, int64(session), msg.getSessionID(), "bad session")
	if !assert.Equal(t, int64(_type), msg.getTypeID(), "bad message type") {
		t.FailNow()
	}

	e := msg.(*errorMsg)
	assert.Equal(t, errorCode, e.Code, "bad error code")
	assert.Equal(t, errorMessage, e.Message, "bad error message")
}
示例#10
0
func TestDecodeResponse(t *testing.T) {
	inner := bytes.Join([][]byte{
		[]byte{0xA2},
		DeTestByteString("id").Data,
		[]byte{0x02},
		DeTestByteString("result").Data,
		[]byte{0x81},
		DeTestByteString("x").Data,
	}, []byte{})
	outer := bytes.Join([][]byte{
		[]byte{0xD8, 0x18, 0x58, byte(len(inner))},
		inner,
	}, []byte{})
	decoder := codec.NewDecoderBytes(outer, cbor)
	var actual Response
	expected := Response{
		ID:     2,
		Result: []interface{}{[]byte("x")},
		Error:  "",
	}
	err := decoder.Decode(&actual)
	if assert.NoError(t, err) {
		assert.Equal(t, expected, actual)
	}
}
示例#11
0
// Basic websocket test
func TestAPITopologyWebsocket(t *testing.T) {
	ts := topologyServer()
	defer ts.Close()
	url := "/api/topology/processes/ws"

	// Not a websocket request
	res, _ := checkGet(t, ts, url)
	if have := res.StatusCode; have != 400 {
		t.Fatalf("Expected status %d, got %d.", 400, have)
	}

	// Proper websocket request
	ts.URL = "ws" + ts.URL[len("http"):]
	dialer := &websocket.Dialer{}
	ws, res, err := dialer.Dial(ts.URL+url, nil)
	ok(t, err)
	defer ws.Close()

	if want, have := 101, res.StatusCode; want != have {
		t.Fatalf("want %d, have %d", want, have)
	}

	_, p, err := ws.ReadMessage()
	ok(t, err)
	var d detailed.Diff
	decoder := codec.NewDecoderBytes(p, &codec.JsonHandle{})
	if err := decoder.Decode(&d); err != nil {
		t.Fatalf("JSON parse error: %s", err)
	}
	equals(t, 6, len(d.Add))
	equals(t, 0, len(d.Update))
	equals(t, 0, len(d.Remove))
}
示例#12
0
文件: decode.go 项目: tacy/dashboard
func (s *Scheme) DecodeToVersionedObject(data []byte) (interface{}, string, string, error) {
	version, kind, err := s.DataVersionAndKind(data)
	if err != nil {
		return nil, "", "", err
	}

	gv, err := unversioned.ParseGroupVersion(version)
	if err != nil {
		return nil, "", "", err
	}

	internalGV, exists := s.InternalVersions[gv.Group]
	if !exists {
		return nil, "", "", fmt.Errorf("no internalVersion specified for %v", gv)
	}

	if len(gv.Version) == 0 && len(internalGV.Version) != 0 {
		return nil, "", "", fmt.Errorf("version not set in '%s'", string(data))
	}
	if kind == "" {
		return nil, "", "", fmt.Errorf("kind not set in '%s'", string(data))
	}
	obj, err := s.NewObject(version, kind)
	if err != nil {
		return nil, "", "", err
	}

	if err := codec.NewDecoderBytes(data, new(codec.JsonHandle)).Decode(obj); err != nil {
		return nil, "", "", err
	}
	return obj, version, kind, nil
}
示例#13
0
func ToServiceArrivedMessage(d eventual2go.Data) eventual2go.Data {
	m := d.(connection.Message).Payload
	var nsm service.ServiceArrived
	dec := codec.NewDecoderBytes([]byte(m[3]), &mh)
	dec.Decode(&nsm)
	return nsm
}
func DecryptAndUnpack(c web.C, out interface{}, secretKey string) err.ErrWriter {
	ew := err.NewErrWriter()

	c.Env[cKey.SecretKey] = secretKey

	// 暗号化データ
	iv := c.Env[cKey.Iv].([]byte)
	cryptData := c.Env[cKey.CryptData].([]byte)

	// decrypt
	ci, err := aes.NewCipher([]byte(secretKey))
	if err != nil {
		return ew.Write(err)
	}
	cbcDecrypter := cipher.NewCBCDecrypter(ci, iv)

	plain := make([]byte, len(cryptData))
	cbcDecrypter.CryptBlocks(plain, cryptData)

	// decode(codec)

	mh := &codec.MsgpackHandle{RawToString: true}
	dec := codec.NewDecoderBytes(plain, mh)
	err = dec.Decode(out)

	if err != nil {
		return ew.Write(err)
	}

	return ew
}
func DecodeFileDownloadResponse(data []byte) (*FileDownload, error) {
	type DownloadResp struct {
		Off        uint32 `json:"off"`
		Size       uint32 `json:"len"`
		Data       []byte `json:"data"`
		ReturnCode int    `json:"rc"`
	}
	resp := &DownloadResp{}

	dec := codec.NewDecoderBytes(data, new(codec.CborHandle))
	err := dec.Decode(&resp)
	if err != nil {
		return nil, util.NewNewtError(fmt.Sprintf("Invalid incoming cbor: %s",
			err.Error()))
	}
	if resp.ReturnCode != 0 {
		return nil, util.NewNewtError(fmt.Sprintf("Target error: %d",
			resp.ReturnCode))
	}
	if err != nil {
		return nil, util.NewNewtError(fmt.Sprintf("Invalid incoming json: %s",
			err.Error()))
	}
	f := &FileDownload{
		Offset: resp.Off,
		Data:   resp.Data,
		Size:   resp.Size,
	}
	return f, nil
}
示例#16
0
func TestAPITopology(t *testing.T) {
	ts := topologyServer()
	defer ts.Close()

	body := getRawJSON(t, ts, "/api/topology")

	var topologies []app.APITopologyDesc
	decoder := codec.NewDecoderBytes(body, &codec.JsonHandle{})
	if err := decoder.Decode(&topologies); err != nil {
		t.Fatalf("JSON parse error: %s", err)
	}
	equals(t, 4, len(topologies))

	for _, topology := range topologies {
		is200(t, ts, topology.URL)

		for _, subTopology := range topology.SubTopologies {
			is200(t, ts, subTopology.URL)
		}

		if have := topology.Stats.EdgeCount; have <= 0 {
			t.Errorf("EdgeCount isn't positive for %s: %d", topology.Name, have)
		}

		if have := topology.Stats.NodeCount; have <= 0 {
			t.Errorf("NodeCount isn't positive for %s: %d", topology.Name, have)
		}

		if have := topology.Stats.NonpseudoNodeCount; have <= 0 {
			t.Errorf("NonpseudoNodeCount isn't positive for %s: %d", topology.Name, have)
		}
	}
}
示例#17
0
// loadContents loads or calculates and saves package contents
func (collection *PackageCollection) loadContents(p *Package, packagePool aptly.PackagePool) []string {
	encoded, err := collection.db.Get(p.Key("xC"))
	if err == nil {
		contents := []string{}

		decoder := codec.NewDecoderBytes(encoded, collection.codecHandle)
		err = decoder.Decode(&contents)
		if err != nil {
			panic("unable to decode contents")
		}

		return contents
	}

	if err != database.ErrNotFound {
		panic("unable to load contents")
	}

	contents := p.CalculateContents(packagePool)

	var buf bytes.Buffer
	err = codec.NewEncoder(&buf, collection.codecHandle).Encode(contents)
	if err != nil {
		panic("unable to encode contents")
	}

	err = collection.db.Put(p.Key("xC"), buf.Bytes())
	if err != nil {
		panic("unable to save contents")
	}

	return contents
}
示例#18
0
文件: session.go 项目: jmcarbo/kocha
// Load returns the session data that extract from cookie value.
// The key is stored session cookie value.
func (store *SessionCookieStore) Load(key string) (sess Session) {
	defer func() {
		if err := recover(); err != nil {
			if err, ok := err.(error); ok {
				panic(NewErrSession(err.Error()))
			}
			panic(err)
		}
	}()
	decoded, err := store.decode(key)
	if err != nil {
		panic(err)
	}
	unsigned, err := store.verify(decoded)
	if err != nil {
		panic(err)
	}
	decrypted, err := store.decrypt(unsigned)
	if err != nil {
		panic(err)
	}
	if err := codec.NewDecoderBytes(decrypted, &codec.MsgpackHandle{}).Decode(&sess); err != nil {
		panic(err)
	}
	return sess
}
示例#19
0
// 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
}
示例#20
0
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
}
示例#21
0
// Unpacks an event fom MsgPack bytes
func unPackBytes(b []byte) (*Event, error) {
	var mh codec.MsgpackHandle
	var v interface{}

	dec := codec.NewDecoderBytes(b, &mh)

	err := dec.Decode(&v)
	if err != nil {
		return nil, err
	}

	// get the event headers
	h, ok := v.([]interface{})[0].(map[interface{}]interface{})
	if !ok {
		return nil, errors.New("zerorpc/event interface conversion error")
	}

	header := make(map[string]interface{})

	for k, v := range h {
		switch t := v.(type) {
		case []byte:
			header[k.(string)] = string(t)

		default:
			header[k.(string)] = t
		}
	}

	// get the event name
	n, ok := v.([]interface{})[1].([]byte)
	if !ok {
		return nil, errors.New("zerorpc/event interface conversion error")
	}

	// get the event args
	args := make([]interface{}, 0)

	for i := 2; i < len(v.([]interface{})); i++ {
		t := v.([]interface{})[i]

		switch t.(type) {
		case []interface{}:
			for _, a := range t.([]interface{}) {
				args = append(args, convertValue(a))
			}

		default:
			args = append(args, convertValue(t))
		}
	}

	e := Event{
		Header: header,
		Name:   string(n),
		Args:   args,
	}

	return &e, nil
}
示例#22
0
func isSaltpackBinary(b []byte, sc *StreamClassification) bool {
	if len(b) < 2 {
		return false
	}

	if b[0] <= 0x92 || b[0] >= 0x9a {
		return false
	}
	tmp := make([]byte, len(b))
	copy(tmp, b)

	// Hack -- make this a 3-value Msgpack Array, since we only care about the
	// first 3 fields, and don't want to bother slurping in more than that.
	tmp[0] = 0x93
	var mh codec.MsgpackHandle
	var sphp saltpackHeaderPrefix
	if err := codec.NewDecoderBytes(tmp, &mh).Decode(&sphp); err != nil {
		return false
	}
	if sphp.FormatName != saltpack.SaltpackFormatName {
		return false
	}
	switch sphp.Type {
	case saltpack.MessageTypeEncryption:
		sc.Type = CryptoMessageTypeEncryption
	case saltpack.MessageTypeAttachedSignature:
		sc.Type = CryptoMessageTypeAttachedSignature
	case saltpack.MessageTypeDetachedSignature:
		sc.Type = CryptoMessageTypeDetachedSignature
	default:
		return false
	}
	sc.Format = CryptoMessageFormatSaltpack
	return true
}
示例#23
0
func (s *Scheme) DecodeToVersionedObject(data []byte) (interface{}, string, string, error) {
	gvk, err := s.DataKind(data)
	if err != nil {
		return nil, "", "", err
	}

	internalGV, exists := s.InternalVersions[gvk.Group]
	if !exists {
		return nil, "", "", fmt.Errorf("no internalVersion specified for %v", gvk)
	}

	if len(gvk.Group) == 0 && len(internalGV.Group) != 0 {
		return nil, "", "", fmt.Errorf("group not set in '%s'", string(data))
	}
	if len(gvk.Version) == 0 && len(internalGV.Version) != 0 {
		return nil, "", "", fmt.Errorf("version not set in '%s'", string(data))
	}
	if gvk.Kind == "" {
		return nil, "", "", fmt.Errorf("kind not set in '%s'", string(data))
	}

	obj, err := s.NewObject(gvk.GroupVersion().String(), gvk.Kind)
	if err != nil {
		return nil, "", "", err
	}

	if err := codec.NewDecoderBytes(data, new(codec.JsonHandle)).Decode(obj); err != nil {
		return nil, "", "", err
	}
	return obj, gvk.GroupVersion().String(), gvk.Kind, nil
}
示例#24
0
func main() {
	jh := new(codec.JsonHandle)
	u := &user.User{
		Name:  "Inigo Montoya",
		Email: "*****@*****.**",
	}

	var out []byte
	err := codec.NewEncoderBytes(&out, jh).Encode(&u)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Println(string(out))

	var u2 user.User
	err = codec.NewDecoderBytes(out, jh).Decode(&u2)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Println(u2)
}
示例#25
0
func TestGroupVersionUnmarshalJSON(t *testing.T) {
	cases := []struct {
		input  []byte
		expect GroupVersion
	}{
		{[]byte(`{"val": "v1"}`), GroupVersion{"", "v1"}},
		{[]byte(`{"val": "extensions/v1beta1"}`), GroupVersion{"extensions", "v1beta1"}},
	}

	for _, c := range cases {
		var result GroupVersionHolder
		// test golang lib's JSON codec
		if err := json.Unmarshal([]byte(c.input), &result); err != nil {
			t.Errorf("JSON codec failed to unmarshal input '%v': %v", c.input, err)
		}
		if !reflect.DeepEqual(result.GV, c.expect) {
			t.Errorf("JSON codec failed to unmarshal input '%s': expected %+v, got %+v", c.input, c.expect, result.GV)
		}
		// test the Ugorji codec
		if err := codec.NewDecoderBytes(c.input, new(codec.JsonHandle)).Decode(&result); err != nil {
			t.Errorf("Ugorji codec failed to unmarshal input '%v': %v", c.input, err)
		}
		if !reflect.DeepEqual(result.GV, c.expect) {
			t.Errorf("Ugorji codec failed to unmarshal input '%s': expected %+v, got %+v", c.input, c.expect, result.GV)
		}
	}
}
示例#26
0
// DecodeIntoWithSpecifiedVersionKind compares the passed in requestGroupVersionKind
// with data.Version and data.Kind, defaulting data.Version and
// data.Kind to the specified value if they are empty, or generating an error if
// data.Version and data.Kind are not empty and differ from the specified value.
// The function then implements the functionality of DecodeInto.
// If specifiedVersion and specifiedKind are empty, the function degenerates to
// DecodeInto.
func (s *Scheme) DecodeIntoWithSpecifiedVersionKind(data []byte, obj interface{}, requestedGVK unversioned.GroupVersionKind) error {
	if len(data) == 0 {
		return errors.New("empty input")
	}
	dataGVK, err := s.DataKind(data)
	if err != nil {
		return err
	}
	if len(dataGVK.Group) == 0 {
		dataGVK.Group = requestedGVK.Group
	}
	if len(dataGVK.Version) == 0 {
		dataGVK.Version = requestedGVK.Version
	}
	if len(dataGVK.Kind) == 0 {
		dataGVK.Kind = requestedGVK.Kind
	}

	if len(requestedGVK.Group) > 0 && requestedGVK.Group != dataGVK.Group {
		return errors.New(fmt.Sprintf("The fully qualified kind in the data (%v) does not match the specified apiVersion(%v)", dataGVK, requestedGVK))
	}
	if len(requestedGVK.Version) > 0 && requestedGVK.Version != dataGVK.Version {
		return errors.New(fmt.Sprintf("The fully qualified kind in the data (%v) does not match the specified apiVersion(%v)", dataGVK, requestedGVK))
	}
	if len(requestedGVK.Kind) > 0 && requestedGVK.Kind != dataGVK.Kind {
		return errors.New(fmt.Sprintf("The fully qualified kind in the data (%v) does not match the specified apiVersion(%v)", dataGVK, requestedGVK))
	}

	objGVK, err := s.ObjectKind(obj)
	if err != nil {
		return err
	}
	// Assume objects with unset fields are being unmarshalled into the
	// correct type.
	if len(dataGVK.Group) == 0 {
		dataGVK.Group = objGVK.Group
	}
	if len(dataGVK.Version) == 0 {
		dataGVK.Version = objGVK.Version
	}
	if len(dataGVK.Kind) == 0 {
		dataGVK.Kind = objGVK.Kind
	}

	external, err := s.NewObject(dataGVK.GroupVersion().String(), dataGVK.Kind)
	if err != nil {
		return err
	}
	if err := codec.NewDecoderBytes(data, new(codec.JsonHandle)).Decode(external); err != nil {
		return err
	}
	flags, meta := s.generateConvertMeta(dataGVK.GroupVersion(), objGVK.GroupVersion(), external)
	if err := s.converter.Convert(external, obj, flags, meta); err != nil {
		return err
	}

	// Version and Kind should be blank in memory.
	return s.SetVersionAndKind("", "", obj)
}
示例#27
0
func testdecode(b []byte) {
	var v map[string]interface{} // value to decode/encode into
	//dec = codec.NewDecoder(r, &mh)
	dec := codec.NewDecoderBytes(b, &mh)
	_ = dec.Decode(&v)

	//fmt.Println("v=",v,"\n\n")
}
示例#28
0
文件: remote.go 项目: romtastic/aptly
// Decode decodes msgpack representation into RemoteRepo
func (repo *RemoteRepo) Decode(input []byte) error {
	decoder := codec.NewDecoderBytes(input, &codec.MsgpackHandle{})
	err := decoder.Decode(repo)
	if err != nil {
		return err
	}
	return repo.prepare()
}
示例#29
0
/*
   github.com/ugorji/go/codec
*/
func BenchmarkUgirjiSmall(b *testing.B) {
	for i := 0; i < b.N; i++ {
		decoder := codec.NewDecoderBytes(smallFixture, new(codec.JsonHandle))
		data := new(SmallPayload)
		data.CodecDecodeSelf(decoder)

		nothing(data.Uuid, data.Tz, data.Ua, data.St)
	}
}
示例#30
0
文件: main.go 项目: nopsky/gameserver
func decode(reqData []byte, _req interface{}) (err error) {
	if len(reqData) == 0 {
		return
	}
	var mh codec.MsgpackHandle
	decode := codec.NewDecoderBytes(reqData, &mh)
	err = decode.Decode(_req)
	return
}