首頁  >  文章  >  後端開發  >  golang protobuf 安裝

golang protobuf 安裝

WBOY
WBOY原創
2023-05-18 21:34:361159瀏覽

golang是目前非常流行的程式語言,它同時也是Google主推的程式語言之一。 Google在開發過程中使用了protobuf(Protocol Buffers),因此golang也提供了對protobuf的支援。 protobuf是一種輕量級的資料序列化協議,它可以被用於資料交換和持久化。在golang中使用protobuf可以讓程式的效能更高、更穩定。本文將介紹golang protobuf的安裝方法。

  1. 安裝protobuf
    Golang使用的protobuf版本需要先安裝,可以透過以下方式安裝:

先下載對應版本的protobuf,下載位址為:https ://github.com/protocolbuffers/protobuf/releases

以protobuf版本3.18.0為例,下載後解壓縮:

tar -xzf protobuf-all-3.18.0.tar.gz
cd protobuf-3.18.0

進入protobuf的目錄中,執行以下指令安裝:

./configure
make
make check
sudo make install
sudo ldconfig # refresh shared library cache.

註:如果遇到「libtool: install: /usr/bin/install -c .libs/x86_64-linux-gnu/libprotobuf.so.25.0.0 /usr/local/lib/libprotobuf. so.25.0.0」的類似訊息,可以忽略。

安裝完成後,執行以下命令驗證:

protoc --version

顯示以下資訊表示安裝成功:

libprotoc 3.18.0
  1. 安裝golang protobuf外掛程式
    使用protobuf需要在golang中安裝protobuf插件,可以透過以下命令安裝:
go get -u github.com/golang/protobuf/protoc-gen-go

安裝完成後,可以驗證是否安裝成功:

which protoc-gen-go

顯示如下資訊表示安裝成功:

$GOPATH/bin/protoc-gen-go
  1. 使用golang protobuf外掛程式
    安裝完成protobuf外掛後,就可以使用golang的protobuf套件了。在golang編寫的protobuf檔案轉換成golang程式碼並使用的過程如下:

第一步,編寫protobuf檔案。範例:

syntax = "proto3";

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

第二步,使用protobuf編譯器將protobuf檔案轉換成golang程式碼:

protoc --go_out=. person.proto

執行完後,會產生person.pb.go文件,檔案內容如下:

package main

import (
  "fmt"
  "github.com/golang/protobuf/proto"
)

type Person struct {
  Name     string  `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
  Age      int32   `protobuf:"varint,2,opt,name=age,proto3" json:"age,omitempty"`
  Address  string  `protobuf:"bytes,3,opt,name=address,proto3" json:"address,omitempty"`
}

func main() {
  person := &Person{
    Name: "John",
    Age:     25,
    Address: "New york",
  }
  data, _ := proto.Marshal(person)
  fmt.Println(data)
  newperson := &Person{}
  _ = proto.Unmarshal(data, newperson)
  fmt.Printf("Name: %s, Age: %d, Address: %s
", newperson.Name, newperson.Age, newperson.Address)
}

第三步,使用產生的程式碼進行開發。在main函數中,序列化和反序列化Person物件並輸出。

總結:
golang在使用protobuf時需要先安裝protobuf和golang protobuf外掛。透過編寫protobuf文件,使用protobuf編譯器將其轉換成golang程式碼並使用。使用protobuf可以使程式的效能更高、更穩定。

以上是golang protobuf 安裝的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:idea 搭建golang下一篇:idea 搭建golang