Skip to content

Instantly share code, notes, and snippets.

@qneyrat
Last active September 11, 2017 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qneyrat/0cdcfd10c7348e661e152dee16609eca to your computer and use it in GitHub Desktop.
Save qneyrat/0cdcfd10c7348e661e152dee16609eca to your computer and use it in GitHub Desktop.
Blog Eleven Labs : Présentation de Protobuf
package main
import (
"bufio"
"bytes"
fmt "fmt"
"log"
"net/http"
proto "github.com/golang/protobuf/proto"
)
func main() {
post := &Post{}
resp, err := http.Get("http://127.0.0.1:8080/posts/1.proto")
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";
message Post {
int32 id = 1;
string title = 2;
string author = 3;
}
package main
import (
"encoding/json"
"log"
"net/http"
proto "github.com/golang/protobuf/proto"
)
var post = &Post{
Id: 1,
Title: "My awesome article",
Author: "Quentin Neyrat",
}
func jsonHandler(w http.ResponseWriter, r *http.Request) {
out, err := json.Marshal(post)
if err != nil {
log.Fatalln("Failed to serialize post in json:", err)
}
w.Write(out)
}
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.json", jsonHandler)
http.HandleFunc("/posts/1.proto", protoHandler)
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment