Skip to content

Instantly share code, notes, and snippets.

@aldy505
Created May 15, 2022 07:30
Show Gist options
  • Save aldy505/51493cd3026c6e2be563286e6319532a to your computer and use it in GitHub Desktop.
Save aldy505/51493cd3026c6e2be563286e6319532a to your computer and use it in GitHub Desktop.
Proto2http generated client & server samples for router_guide.proto
/**
* Points are represented as latitude-longitude pairs in the E7 representation
* (degrees multiplied by 10**7 and rounded to the nearest integer).
* Latitudes should be in the range +/- 90 degrees and longitude should be in
* the range +/- 180 degrees (inclusive).
*/
type Point = {
latitude: number
longitude: number
}
/**
* A feature names something at a given point.
* If a feature could not be named, the name is empty.
*/
type Feature = {
/**
* The name of the feature.
*/
name: string
/**
* The point where the feature is detected.
*/
location: Point
}
/**
* A latitude-longitude rectangle, represented as two diagonally opposite
* points "lo" and "hi".
*/
type Rectangle = {
/**
* One corner of the rectangle.
*/
lo: Point
/**
* The other corner of the rectangle.
*/
hi: Point
}
/**
* A RouteSummary is received in response to a RecordRoute rpc.
* It contains the number of individual points received, the number of
* detected features, and the total distance covered as the cumulative sum of
* the distance between each point.
*/
type RouteSummary = {
/**
* The number of points received.
*/
point_count: number
/**
* The number of known features passed while traversing the route.
*/
feature_count: number
/**
* The distance covered in metres.
*/
distance: number
/**
* The duration of the traversal in seconds.
*/
elapsed_time: number
}
/**
* A RouteNote is a message sent while at a given point.
*/
type RouteNote = {
/**
* The location from which the message is sent.
*/
location: Point
/**
* The message to be sent.
*/
message: string
}
/**
* Interface exported by the server.
*/
export class RouteGuideClient {
_baseUrl: string
constructor(baseUrl?: string) {
if (baseUrl === "" || baseUrl == null) {
this._baseUrl = "http://localhost:3000";
} else {
this._baseUrl = baseUrl;
}
}
/**
* A simple RPC.
*
* Obtains the feature at a given position.
*
* A feature with an empty name is returned if there's no feature at the given
* position.
*/
public async GetFeature(input: Point): Promise<Feature> {
const request = await fetch(
new URL("GetFeature", this._baseUrl).toString(),
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(input),
}
);
const body = await request.json();
return body;
}
/**
* A server-to-client streaming RPC.
*
* Obtains the Features available within the given Rectangle. Results are
* streamed rather than returned at once (e.g. in a response message with a
* repeated field), as the rectangle may cover a large area and contain a
* huge number of features.
*/
public async ListFeatures(input: Rectangle): Promise<Feature> {
const request = await fetch(
new URL("ListFeatures", this._baseUrl).toString(),
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(input),
}
);
const body = await request.json();
return body;
}
/**
* A client-to-server streaming RPC.
*
* Accepts a stream of Points on a route being traversed, returning a
* RouteSummary when traversal is completed.
*/
public async RecordRoute(input: Point): Promise<RouteSummary> {
const request = await fetch(
new URL("RecordRoute", this._baseUrl).toString(),
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(input),
}
);
const body = await request.json();
return body;
}
/**
* A Bidirectional streaming RPC.
*
* Accepts a stream of RouteNotes sent while a route is being traversed,
* while receiving other RouteNotes (e.g. from other users).
*/
public async RouteChat(input: RouteNote): Promise<RouteNote> {
const request = await fetch(
new URL("RouteChat", this._baseUrl).toString(),
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(input),
}
);
const body = await request.json();
return body;
}
}
package routeguide
import (
"context"
"encoding/json"
"net/http"
"github.com/go-chi/chi/v5"
)
// Points are represented as latitude-longitude pairs in the E7 representation
// (degrees multiplied by 10**7 and rounded to the nearest integer).
// Latitudes should be in the range +/- 90 degrees and longitude should be in
// the range +/- 180 degrees (inclusive).
type Point struct {
Latitude int32 `json:"latitude"`
Longitude int32 `json:"longitude"`
}
// A feature names something at a given point.
// If a feature could not be named, the name is empty.
type Feature struct {
// The name of the feature.
Name string `json:"name"`
// The point where the feature is detected.
Location Point `json:"location"`
}
// A latitude-longitude rectangle, represented as two diagonally opposite
// points "lo" and "hi".
type Rectangle struct {
// One corner of the rectangle.
Lo Point `json:"lo"`
// The other corner of the rectangle.
Hi Point `json:"hi"`
}
// A RouteSummary is received in response to a RecordRoute rpc.
// It contains the number of individual points received, the number of
// detected features, and the total distance covered as the cumulative sum of
// the distance between each point.
type RouteSummary struct {
// The number of points received.
PointCount int32 `json:"point_count"`
// The number of known features passed while traversing the route.
FeatureCount int32 `json:"feature_count"`
// The distance covered in metres.
Distance int32 `json:"distance"`
// The duration of the traversal in seconds.
ElapsedTime int32 `json:"elapsed_time"`
}
// A RouteNote is a message sent while at a given point.
type RouteNote struct {
// The location from which the message is sent.
Location Point `json:"location"`
// The message to be sent.
Message string `json:"message"`
}
type RouteGuideServer interface {
// A simple RPC.
// Obtains the feature at a given position.
// A feature with an empty name is returned if there's no feature at the given
// position.
GetFeature(ctx context.Context, req *Point) (*Feature, error)
// A server-to-client streaming RPC.
// Obtains the Features available within the given Rectangle. Results are
// streamed rather than returned at once (e.g. in a response message with a
// repeated field), as the rectangle may cover a large area and contain a
// huge number of features.
ListFeatures(ctx context.Context, req *Rectangle) (*Feature, error)
// A client-to-server streaming RPC.
// Accepts a stream of Points on a route being traversed, returning a
// RouteSummary when traversal is completed.
RecordRoute(ctx context.Context, req *Point) (*RouteSummary, error)
// A Bidirectional streaming RPC.
// Accepts a stream of RouteNotes sent while a route is being traversed,
// while receiving other RouteNotes (e.g. from other users).
RouteChat(ctx context.Context, req *RouteNote) (*RouteNote, error)
}
// Interface exported by the server.
func NewRouteGuideServer(implementation RouteGuideServer) http.Handler {
mux := chi.NewMux()
mux.Post("/GetFeature", func(w http.ResponseWriter, r *http.Request) {
var req Point
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
resp, err := implementation.GetFeature(r.Context(), &req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
err = json.NewEncoder(w).Encode(resp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
mux.Post("/ListFeatures", func(w http.ResponseWriter, r *http.Request) {
var req Rectangle
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
resp, err := implementation.ListFeatures(r.Context(), &req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
err = json.NewEncoder(w).Encode(resp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
mux.Post("/RecordRoute", func(w http.ResponseWriter, r *http.Request) {
var req Point
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
resp, err := implementation.RecordRoute(r.Context(), &req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
err = json.NewEncoder(w).Encode(resp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
mux.Post("/RouteChat", func(w http.ResponseWriter, r *http.Request) {
var req RouteNote
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
resp, err := implementation.RouteChat(r.Context(), &req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
err = json.NewEncoder(w).Encode(resp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
return mux
}
package routeguide
import (
"context"
"encoding/json"
"net/http"
)
// Points are represented as latitude-longitude pairs in the E7 representation
// (degrees multiplied by 10**7 and rounded to the nearest integer).
// Latitudes should be in the range +/- 90 degrees and longitude should be in
// the range +/- 180 degrees (inclusive).
type Point struct {
Latitude int32 `json:"latitude"`
Longitude int32 `json:"longitude"`
}
// A feature names something at a given point.
// If a feature could not be named, the name is empty.
type Feature struct {
// The name of the feature.
Name string `json:"name"`
// The point where the feature is detected.
Location Point `json:"location"`
}
// A latitude-longitude rectangle, represented as two diagonally opposite
// points "lo" and "hi".
type Rectangle struct {
// One corner of the rectangle.
Lo Point `json:"lo"`
// The other corner of the rectangle.
Hi Point `json:"hi"`
}
// A RouteSummary is received in response to a RecordRoute rpc.
// It contains the number of individual points received, the number of
// detected features, and the total distance covered as the cumulative sum of
// the distance between each point.
type RouteSummary struct {
// The number of points received.
PointCount int32 `json:"point_count"`
// The number of known features passed while traversing the route.
FeatureCount int32 `json:"feature_count"`
// The distance covered in metres.
Distance int32 `json:"distance"`
// The duration of the traversal in seconds.
ElapsedTime int32 `json:"elapsed_time"`
}
// A RouteNote is a message sent while at a given point.
type RouteNote struct {
// The location from which the message is sent.
Location Point `json:"location"`
// The message to be sent.
Message string `json:"message"`
}
type RouteGuideServer interface {
// A simple RPC.
// Obtains the feature at a given position.
// A feature with an empty name is returned if there's no feature at the given
// position.
GetFeature(ctx context.Context, req *Point) (*Feature, error)
// A server-to-client streaming RPC.
// Obtains the Features available within the given Rectangle. Results are
// streamed rather than returned at once (e.g. in a response message with a
// repeated field), as the rectangle may cover a large area and contain a
// huge number of features.
ListFeatures(ctx context.Context, req *Rectangle) (*Feature, error)
// A client-to-server streaming RPC.
// Accepts a stream of Points on a route being traversed, returning a
// RouteSummary when traversal is completed.
RecordRoute(ctx context.Context, req *Point) (*RouteSummary, error)
// A Bidirectional streaming RPC.
// Accepts a stream of RouteNotes sent while a route is being traversed,
// while receiving other RouteNotes (e.g. from other users).
RouteChat(ctx context.Context, req *RouteNote) (*RouteNote, error)
}
// Interface exported by the server.
func NewRouteGuideServer(implementation RouteGuideServer) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/GetFeature", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var req Point
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
resp, err := implementation.GetFeature(r.Context(), &req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
err = json.NewEncoder(w).Encode(resp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
mux.HandleFunc("/ListFeatures", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var req Rectangle
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
resp, err := implementation.ListFeatures(r.Context(), &req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
err = json.NewEncoder(w).Encode(resp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
mux.HandleFunc("/RecordRoute", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var req Point
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
resp, err := implementation.RecordRoute(r.Context(), &req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
err = json.NewEncoder(w).Encode(resp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
mux.HandleFunc("/RouteChat", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var req RouteNote
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
resp, err := implementation.RouteChat(r.Context(), &req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
err = json.NewEncoder(w).Encode(resp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
return mux
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment