GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — CoderNoteBook/note/protobuff_with_golang_tutorial.md at master · BBLiu-coder/CoderNoteBook

Expand file tree

/

protobuff_with_golang_tutorial.md

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
73 lines (56 loc) · 1.05 KB
/

protobuff_with_golang_tutorial.md

Copy path

File metadata and controls

73 lines (56 loc) · 1.05 KB
Raw
Copy raw file
Download raw file
Outline
Edit and raw actions

golang 使用 protobuff hello world 教程

为什么要protobuff ?

把关于我对data represent的理解,以及为什么要用pb这类组件的原因写在blog上面了:
https://www.jianshu.com/p/131f0bf218ef

hello world

目录结构:

.
├── person.pb.go
├── person.proto
└── server.go

person.proto

syntax = "proto3";

package main;

message Person {
    string name = 1;
    int32 age = 2;
}

server.go

package main

import (
	"fmt"
	"log"

	proto "github.com/golang/protobuf/proto"
)

func main() {
	fmt.Println("hello proto")

	elliot := &Person{
		Name: "elliot",
		Age:  24,
	}

	data, err := proto.Marshal(elliot)
	if err != nil {
		log.Fatal("Marshal error : ", err)
	}
	fmt.Println(data)

	newElliot := &Person{}
	err = proto.Unmarshal(data, newElliot)
	if err != nil {
		log.Fatal("unmarshal error : ", err)
	}

	fmt.Println(newElliot.GetAge())
	fmt.Println(newElliot.GetName())
}

构建:

# 根据proto,导出.go 文件
protoc --go_out=./ *.proto

# run
go run server.go person.pb.go
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.