Skip to content

Instantly share code, notes, and snippets.

@jtbonhomme
Last active February 6, 2018 14:34
Show Gist options
  • Save jtbonhomme/e23e4b30a656301a26f4f38958cfca0b to your computer and use it in GitHub Desktop.
Save jtbonhomme/e23e4b30a656301a26f4f38958cfca0b to your computer and use it in GitHub Desktop.
gRPC example
package main
import (
"bufio"
"bytes"
"fmt"
"log"
"net/http"
pb "test_protobuf/post"
proto "github.com/golang/protobuf/proto"
)
func main() {
post := &pb.Post{}
resp, err := http.Get("http://127.0.0.1:8080/posts/1")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
sca := bufio.NewScanner(resp.Body)
sca.Split(bufio.ScanRunes)
var buf bytes.Buffer
for sca.Scan() {
buf.WriteString(sca.Text())
}
err = proto.Unmarshal(buf.Bytes(), post)
if err != nil {
log.Fatal("unmarshaling error: ", err)
}
fmt.Printf("Id: %d \n", post.GetId())
fmt.Printf("Title: %s \n", post.GetTitle())
fmt.Printf("Author: %s \n", post.GetAuthor())
}
syntax = "proto3";
package post;
message Post {
int32 id = 1;
string title = 2;
string author = 3;
}
package main
import (
"log"
"net/http"
pb "test_protobuf/post"
proto "github.com/golang/protobuf/proto"
)
var post = &pb.Post{
Id: 1,
Title: "My awesome article",
Author: "Quentin Neyrat",
}
func protoHandler(w http.ResponseWriter, r *http.Request) {
out, err := proto.Marshal(post)
if err != nil {
log.Fatalln("Failed to serialize post in protobuf:", err)
}
w.Write(out)
}
func main() {
http.HandleFunc("/posts/1", protoHandler)
http.ListenAndServe(":8080", nil)
}
@jtbonhomme
Copy link
Author

jtbonhomme commented Feb 6, 2018

$ mkdir post
$ mv post.proto post
$ cd post
$ protoc --proto_path=. --go_out=. post.proto
$ cd ..
$ go run server.go
(on another terminal)
$ go run client.go

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment