Compare RPC streaming and HTTP transport
Compare RPC streaming and HTTP transport
RPC (remote procedure call) defines named remote operations and typed inputs and outputs. A unary RPC exchanges one request and one response; server streaming sends many responses; client streaming sends many requests; bidirectional streaming permits both sides to send independently. gRPC commonly uses HTTP/2 and Protobuf, whereas ordinary HTTP APIs can expose resources and stream data in many formats. Choose based on contracts, clients, intermediaries and flow control, not on a claim that one is always faster.
package main
import ( "encoding/json" "fmt" "io" "net/http" "net/http/httptest")
type Event struct{ ID int }
func main() { s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/x-ndjson") enc := json.NewEncoder(w) for _, id := range []int{1, 2} { if err := enc.Encode(Event{id}); err != nil { return } w.(http.Flusher).Flush() } })) defer s.Close() resp, err := s.Client().Get(s.URL) if err != nil { panic(err) } defer resp.Body.Close() d := json.NewDecoder(resp.Body) for { var e Event err := d.Decode(&e) if err == io.EOF { break } if err != nil { panic(err) } fmt.Println(e.ID) }}This local HTTP example streams newline-delimited JSON (NDJSON), not gRPC. Each Encode emits a record and newline. The client decodes records until EOF; flush requests transmission but does not guarantee immediate delivery through proxies. For production bound message sizes, check HTTP status, set cancellation and handle interrupted streams.
Expected output:
12Distinguish end of stream from malformed records
package main
import ( "encoding/json" "fmt" "io" "strings")
func main() { d := json.NewDecoder(strings.NewReader("{\"id\":1}\n{")) var m map[string]int fmt.Println(d.Decode(&m) == nil, m["id"]) err := d.Decode(&m) fmt.Println(err != nil, err == io.EOF)}A broken final record is not a clean EOF. In gRPC the final status also matters, even after messages have arrived. Backpressure limits how quickly a sender can proceed; slow receivers must not trigger unbounded buffering. The examples do not test HTTP/2 multiplexing or gRPC flow control.
Expected output:
true 1true falseTry it locally
Decode two NDJSON integers, 4 and 7, until EOF. Print their sum; reject any other decoding error.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Service protocols and cloud 01: Compare RPC streaming and HTTP transport
Check the lesson objective before moving on.
Which RPC shape sends many responses to one request?
What does a flush guarantee about a proxy?