Last active
February 6, 2018 14:34
-
-
Save jtbonhomme/e23e4b30a656301a26f4f38958cfca0b to your computer and use it in GitHub Desktop.
gRPC example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
syntax = "proto3"; | |
package post; | |
message Post { | |
int32 id = 1; | |
string title = 2; | |
string author = 3; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.