funcpromptForAddress(r io.Reader)(*pb.Person, error) { // A protocol buffer can be created like any struct. p := &pb.Person{}
rd := bufio.NewReader(r) fmt.Print("Enter person ID number: ") // An int32 field in the .proto file is represented as an int32 field // in the generated Go struct. if _, err := fmt.Fscanf(rd, "%d\n", &p.Id); err != nil { return p, err }
fmt.Print("Enter name: ") name, err := rd.ReadString('\n') if err != nil { return p, err } // A string field in the .proto file results in a string field in Go. // We trim the whitespace because rd.ReadString includes the trailing // newline character in its output. p.Name = strings.TrimSpace(name)
// Main reads the entire person from a file, adds one person based on // user input, then writes it back out to the same file. funcmain() { iflen(os.Args) != 2 { log.Fatalf("Usage: %s PERSON_FILE\n", os.Args[0]) } fname := os.Args[1]
// Read the existing address book. in, err := ioutil.ReadFile(fname) if err != nil { if os.IsNotExist(err) { fmt.Printf("%s: File not found. Creating new file.\n", fname) } else { log.Fatalln("Error reading file:", err) } }
// [START marshal_proto] person := &pb.Person{} // [START_EXCLUDE] if err := proto.Unmarshal(in, person); err != nil { log.Fatalln("Failed to parse address book:", err) } bs, _ := json.Marshal(person) log.Printf("Got PERSON : %v \n", string(bs))
// Add an address. newPerson, err := promptForAddress(os.Stdin) if err != nil { log.Fatalln("Error with address:", err) } // [END_EXCLUDE]
// Write the new person back to disk. out, err := proto.Marshal(newPerson) if err != nil { log.Fatalln("Failed to encode person:", err) } if err := ioutil.WriteFile(fname, out, 0644); err != nil { log.Fatalln("Failed to write person:", err) } // [END marshal_proto] }
执行代码: 添加一个Person数据并序列化到本地:
1 2 3 4 5 6
[root addPerson]# go run add.go ./per ./per: File not found. Creating new file. 2024/01/15 16:11:51 Got PERSON : {} Enter person ID number: 14930 Enter name: HowardSUN Enter email address (blank for none): 14930@qq.com