예제 #1
0
파일: main.go 프로젝트: shaalx/protobuf
func marchalText() {
	m := &MyMessage{Count: proto.Int32(1234), Name: proto.String("protoName"), Quote: proto.String("protoQuote")}
	m.Pet = []string{"1", "2", "3"}
	// MarshalTextString
	fmt.Println("// MarshalTextString...")
	mstr := proto.MarshalTextString(m)
	fmt.Println(mstr)
	var target MyMessage
	proto.UnmarshalText(mstr, &target)
	fmt.Printf("%#v\n", target)
	fmt.Printf("%s\n", target.String())
	fmt.Println("// MarshalTextString...\n")

	// MarshalText
	fmt.Println("// MarshalText...")
	mterr := proto.MarshalText(os.Stdout, m)
	checkerr(mterr)
	var target1 MyMessage
	umterr := proto.UnmarshalText(mstr, &target1)
	checkerr(umterr)
	fmt.Printf("%#v\n", target1)
	fmt.Println(target1.String())
	fmt.Println("// MarshalText...\n")

	// Marshal
	fmt.Println("// Marshal...")
	data, _ := proto.Marshal(m)
	fmt.Println(data)
	var target2 MyMessage
	uerr := proto.Unmarshal(data, &target2)
	checkerr(uerr)
	fmt.Printf("%#v\n", target2)
	fmt.Printf("%s\n", target2.String())
	fmt.Println("// Marshal...\n")

	// // MarshalSet
	// fmt.Println("// MarshalSet...")
	// var mset proto.MessageSet
	// merr := mset.Marshal(m)
	// checkerr(merr)
	// fmt.Println(mset.Item)
	// fmt.Println(mset.XXX_unrecognized)
	// var target3 MyMessage
	// mset.Unmarshal(&target3)
	// fmt.Printf("%#v\n", target3)
}
예제 #2
0
func BenchmarkUnMarshalText(b *testing.B) {
	var msg_new MyMessage
	for i := 0; i < b.N; i++ {
		err := proto.UnmarshalText(marTextStr, &msg_new)
		if checkerr(err) {
			break
		}
	}
}
예제 #3
0
파일: dbtool.go 프로젝트: tstranex/carpcomm
func store(domain *db.Domain) {
	if *table == "station" {
		bytes, err := ioutil.ReadAll(os.Stdin)
		if err != nil {
			log.Fatalf("Error reading proto: %s", err.Error())
		}

		var s pb.Station
		err = proto.UnmarshalText((string)(bytes), &s)
		if err != nil {
			log.Fatalf("Error parsing proto: %s", err.Error())
		}

		stationdb := domain.NewStationDB()
		err = stationdb.Store(&s)
		if err != nil {
			log.Fatalf("Error storing station: %s", err.Error())
		}

		log.Printf("Stored station.")
	} else if *table == "contact" {
		bytes, err := ioutil.ReadAll(os.Stdin)
		if err != nil {
			log.Fatalf("Error reading proto: %s", err.Error())
		}

		var s pb.Contact
		err = proto.UnmarshalText((string)(bytes), &s)
		if err != nil {
			log.Fatalf("Error parsing proto: %s", err.Error())
		}

		contactdb := domain.NewContactDB()
		err = contactdb.Store(&s)
		if err != nil {
			log.Fatalf("Error storing contact: %s", err.Error())
		}

		log.Printf("Stored contact.")
	} else {
		log.Fatalf("Unknown table: %s", *table)
	}
}
예제 #4
0
func TestStringEscaping(t *testing.T) {
	testCases := []struct {
		in  *pb.Strings
		out string
	}{
		{
			// Test data from C++ test (TextFormatTest.StringEscape).
			// Single divergence: we don't escape apostrophes.
			&pb.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and  multiple   spaces")},
			"string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and  multiple   spaces\"\n",
		},
		{
			// Test data from the same C++ test.
			&pb.Strings{StringField: proto.String("\350\260\267\346\255\214")},
			"string_field: \"\\350\\260\\267\\346\\255\\214\"\n",
		},
		{
			// Some UTF-8.
			&pb.Strings{StringField: proto.String("\x00\x01\xff\x81")},
			`string_field: "\000\001\377\201"` + "\n",
		},
	}

	for i, tc := range testCases {
		var buf bytes.Buffer
		if err := proto.MarshalText(&buf, tc.in); err != nil {
			t.Errorf("proto.MarsalText: %v", err)
			continue
		}
		s := buf.String()
		if s != tc.out {
			t.Errorf("#%d: Got:\n%s\nExpected:\n%s\n", i, s, tc.out)
			continue
		}

		// Check round-trip.
		pb := new(pb.Strings)
		if err := proto.UnmarshalText(s, pb); err != nil {
			t.Errorf("#%d: UnmarshalText: %v", i, err)
			continue
		}
		if !proto.Equal(pb, tc.in) {
			t.Errorf("#%d: Round-trip failed:\nstart: %v\n  end: %v", i, tc.in, pb)
		}
	}
}
// Gets spec.
func (c *lmctfyContainerHandler) GetSpec() (*info.ContainerSpec, error) {
	// Run lmctfy spec "container_name" and get spec.
	// Ignore if the container was not found.
	cmd := exec.Command(lmctfyBinary, "spec", string(c.Name))
	data, err := cmd.Output()
	if err != nil && getExitCode(err) != notFoundExitCode {
		return nil, fmt.Errorf("unable to run command %v spec %v: %v", lmctfyBinary, c.Name, err)
	}

	// Parse output into a protobuf.
	pspec := &ContainerSpec{}
	err = proto.UnmarshalText(string(data), pspec)
	if err != nil {
		return nil, err
	}
	spec := protobufToContainerSpec(pspec)
	return spec, nil
}
// Gets full stats.
func (c *lmctfyContainerHandler) GetStats() (*info.ContainerStats, error) {
	// Ignore if the container was not found.
	cmd := exec.Command(lmctfyBinary, "stats", "full", string(c.Name))
	data, err := cmd.Output()
	if err != nil && getExitCode(err) != notFoundExitCode {
		return nil, fmt.Errorf("unable to run command %v stats full %v: %v", lmctfyBinary, c.Name, err)
	}

	// Parse output into a protobuf.
	pstats := &ContainerStats{}
	err = proto.UnmarshalText(string(data), pstats)
	if err != nil {
		return nil, err
	}
	stats := protobufToContainerStats(pstats)
	stats.Timestamp = time.Now()
	return stats, nil
}
예제 #7
0
파일: load.go 프로젝트: pjjw/prometheus
func LoadFromString(configStr string) (Config, error) {
	configProto := pb.PrometheusConfig{}
	if err := proto.UnmarshalText(configStr, &configProto); err != nil {
		return Config{}, err
	}
	if configProto.Global == nil {
		configProto.Global = &pb.GlobalConfig{}
	}
	for _, job := range configProto.Job {
		if job.ScrapeInterval == nil {
			job.ScrapeInterval = proto.String(configProto.Global.GetScrapeInterval())
		}
	}

	config := Config{configProto}
	err := config.Validate()

	return config, err
}
예제 #8
0
func TestLintSatelliteList(t *testing.T) {
	buf, err := ioutil.ReadFile(asciiSatellites)
	if err != nil {
		t.Errorf("Error reading satellites: %s", err.Error())
		return
	}
	sl := &pb.SatelliteList{}
	err = proto.UnmarshalText((string)(buf), sl)
	if err != nil {
		t.Errorf("Error unmarshalling satellites: %s", err.Error())
		return
	}

	if len(sl.Satellite) == 0 {
		t.Error("No satellites found.")
		return
	}

	for _, sat := range sl.Satellite {
		LintSatellite(t, *sat)
	}
}
예제 #9
0
func GetConfig(config_path string, msg proto.Message) error {
	f, err := os.Open(config_path)
	if err != nil {
		return err
	}

	defer f.Close()

	finfo, err := f.Stat()
	if err != nil {
		return err
	}

	buff := make([]byte, finfo.Size()+16)
	n, err := f.Read(buff)
	if err != nil {
		return err
	}

	str := string(buff[:n])

	return proto.UnmarshalText(str, msg)
}
예제 #10
0
파일: main.go 프로젝트: houndbee/pond
func main() {
	flag.Parse()

	if len(*makeAnnounce) > 0 {
		msgBytes, err := ioutil.ReadFile(*makeAnnounce)
		if err != nil {
			panic(err)
		}
		announce := &pond.Message{
			Id:           proto.Uint64(0),
			Time:         proto.Int64(time.Now().Unix()),
			Body:         msgBytes,
			MyNextDh:     []byte{},
			BodyEncoding: pond.Message_RAW.Enum(),
		}
		announceBytes, err := proto.Marshal(announce)
		if err != nil {
			panic(err)
		}
		os.Stdout.Write(announceBytes)
		return
	}

	if len(*baseDirectory) == 0 {
		log.Fatalf("Must give --base-directory")
		return
	}
	configPath := filepath.Join(*baseDirectory, configFilename)

	var identity [32]byte
	if *initFlag {
		if err := os.MkdirAll(*baseDirectory, 0700); err != nil {
			log.Fatalf("Failed to create base directory: %s", err)
			return
		}

		if _, err := io.ReadFull(rand.Reader, identity[:]); err != nil {
			log.Fatalf("Failed to read random bytes: %s", err)
			return
		}

		if err := ioutil.WriteFile(filepath.Join(*baseDirectory, identityFilename), identity[:], 0600); err != nil {
			log.Fatalf("Failed to write identity file: %s", err)
			return
		}

		defaultConfig := &protos.Config{
			Port: proto.Uint32(uint32(*port)),
		}

		configFile, err := os.OpenFile(configPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
		if err != nil {
			log.Fatalf("Failed to create config file: %s", err)
		}
		proto.MarshalText(configFile, defaultConfig)
		configFile.Close()
	}

	identityBytes, err := ioutil.ReadFile(filepath.Join(*baseDirectory, identityFilename))
	if err != nil {
		log.Print("Use --init to setup a new base directory")
		log.Fatalf("Failed to read identity file: %s", err)
		return
	}
	if len(identityBytes) != 32 {
		log.Fatalf("Identity file is not 32 bytes long")
		return
	}
	copy(identity[:], identityBytes)

	config := new(protos.Config)
	configBytes, err := ioutil.ReadFile(configPath)
	if err != nil {
		log.Fatalf("No config file found")
	}

	if err := proto.UnmarshalText(string(configBytes), config); err != nil {
		log.Fatalf("Failed to parse config: %s", err)
	}

	ip := net.IPv4(127, 0, 0, 1) // IPv4 loopback interface

	if config.Address != nil {
		if ip = net.ParseIP(*config.Address); ip == nil {
			log.Fatalf("Failed to parse address from config: %s", ip)
		}
	}

	listenAddr := net.TCPAddr{
		IP:   ip,
		Port: int(*config.Port),
	}
	listener, err := net.ListenTCP("tcp", &listenAddr)
	if err != nil {
		log.Fatalf("Failed to listen on port: %s", err)
	}

	var identityPublic [32]byte
	curve25519.ScalarBaseMult(&identityPublic, &identity)
	identityString := strings.Replace(base32.StdEncoding.EncodeToString(identityPublic[:]), "=", "", -1)
	log.Printf("Started. Listening on port %d with identity %s", listener.Addr().(*net.TCPAddr).Port, identityString)

	server := NewServer(*baseDirectory, config.GetAllowRegistration())

	if *lifelineFd > -1 {
		lifeline := os.NewFile(uintptr(*lifelineFd), "lifeline")
		go func() {
			var buf [1]byte
			lifeline.Read(buf[:])
			os.Exit(255)
		}()
	}

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Printf("Error accepting connection: %s", err)
			continue
		}

		go handleConnection(server, conn, &identity)
	}
}
예제 #11
0
func main() {
	uj := &Pmd.UserJsMessageForwardUserPmd_CS{}
	uj.Msgbytes = []byte(`{"whj":111}`)
	fmt.Println("XXXXX", uj.String(), proto.MarshalTextString(uj))
	rc := &Pmd.ReconnectErrorLoginUserPmd_S{}
	rc.Desc = proto.String(`{"whj":111}`)
	fmt.Println("xxxxx", rc.String(), proto.MarshalTextString(rc), *rc.Desc)
	m := make(map[int]string)
	m[1] = "wabghaijun"
	a := 1
	fmt.Println(protobuf.Encode(&a))
	mset := make(map[int32]proto.Extension)
	//mset[1] = proto.Extension{enc: []byte("sss")}
	//umset, err := proto.MarshalMessageSet(mset)
	var b []byte
	fmt.Println(len(b))
	nmd := &Pmd.ForwardNullUserPmd_CS{}
	nmd1 := &Pmd.ForwardNullUserPmd_CS{}
	nmd2 := &Pmd.ForwardNullUserPmd_CS{}
	cmd3 := &Pmd.RequestCloseNullUserPmd_CS{}
	cmd4 := &Pmd.RequestCloseNullUserPmd_CS{}
	cmd3.Reason = proto.String("2222")
	fmt.Println(proto.GetProperties(reflect.TypeOf(cmd3).Elem()))
	cmd3byte, err1 := proto.Marshal(cmd3)
	if err1 != nil {
		fmt.Println("xxxxxxxxxxx", err1)
	}
	fmt.Println(proto.Unmarshal(cmd3byte, cmd3))
	fmt.Println(mset)
	cmd3test := proto.MarshalTextString(cmd3)
	fmt.Println(cmd3test)
	fmt.Println(proto.UnmarshalText(cmd3test, nmd))
	//nmd.Prototype = proto.Uint64(2)
	nmd.ByCmd = proto.Uint32(0)
	//nmd.ByParam = proto.Uint32(0)
	//nmd.ByCmd = append(nmd.ByCmd, 0)
	//nmd.ByParam = append(nmd.ByParam, 0)
	sendbuf := proto.NewBuffer(nil)
	err := sendbuf.Marshal(nmd)
	if err != nil {
		fmt.Println("1", err)
	}
	nmd.Data = sendbuf.Bytes()
	fmt.Println(nmd, proto.Size(nmd), len(sendbuf.Bytes()))
	fmt.Println(len(sendbuf.Bytes()), sendbuf.Bytes())
	//data := sendbuf.Bytes()
	err = sendbuf.Marshal(cmd3)
	if err != nil {
		fmt.Println("2", err)
	}
	fmt.Println(len(sendbuf.Bytes()), sendbuf.Bytes())
	data := sendbuf.Bytes()
	fmt.Println(len(data), data)
	//data = append(data, byte(1))
	databuf := proto.NewBuffer(data)
	err = databuf.Unmarshal(nmd1)
	if err != nil {
		fmt.Println("3", err)
	}
	//err = databuf.Unmarshal(nmd2)
	err = proto.Unmarshal(data[:2], nmd2)
	if err != nil {
		fmt.Println("4", err)
	}
	err = proto.Unmarshal(data[2:], cmd4)
	//err = databuf.Unmarshal(cmd4)
	if err != nil {
		fmt.Println("5", err)
	}
	fmt.Println(nmd, proto.Size(nmd))
	fmt.Println(nmd1)
	fmt.Println(nmd2)
	fmt.Println(cmd4)
}