Skip to content

Instantly share code, notes, and snippets.

@nathanborror
Last active October 7, 2015 00:21
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 nathanborror/373b95008eab52c4e343 to your computer and use it in GitHub Desktop.
Save nathanborror/373b95008eab52c4e343 to your computer and use it in GitHub Desktop.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let builder = HelloRequest.Builder()
builder.name = "Bob"
do {
let req = try builder.build()
print("Client: My name is \(req.name)")
self.post(req.data())
} catch {
print(error)
}
}
func post(data: NSData) {
let req = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8080")!)
req.HTTPMethod = "POST"
req.HTTPBody = data
let task = NSURLSession.sharedSession().dataTaskWithRequest(req) { data, response, error in
if error != nil {
print(error)
return
}
do {
let reply = try HelloReply.parseFromData(data!)
print("Server: \(reply.response)")
} catch {
print(error)
}
}
task.resume()
}
}
syntax = "proto3";
message HelloRequest {
string name = 2;
}
message HelloReply {
string response = 1;
}
package main
import (
"bytes"
"fmt"
"hello"
"log"
"net/http"
"github.com/golang/protobuf/proto"
)
func handler(w http.ResponseWriter, r *http.Request) {
// Unmarshal incoming request body into a HelloRequest
// object
req := &hello.HelloRequest{}
buf := new(bytes.Buffer)
buf.ReadFrom(r.Body)
if err := proto.Unmarshal(buf.Bytes(), req); err != nil {
log.Fatal("Unmarshaling error: ", err)
return
}
// Marshal a HelloReply object to pass as the response
reply := &hello.HelloReply{Response: "Hello, " + req.Name}
data, err := proto.Marshal(reply)
if err != nil {
log.Fatal("Marshaling error: ", err)
return
}
fmt.Fprintf(w, string(data[:]))
}
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment