Last active
September 11, 2017 21:59
-
-
Save qneyrat/0cdcfd10c7348e661e152dee16609eca to your computer and use it in GitHub Desktop.
Blog Eleven Labs : Présentation de Protobuf
This file contains 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 "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()) | |
} |
This file contains 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"; | |
message Post { | |
int32 id = 1; | |
string title = 2; | |
string author = 3; | |
} |
This file contains 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 ( | |
"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