Introduction
Go (Golang) is renowned for its powerful networking capabilities and performance. Whether you're building web APIs, realtime apps, or microservices, understanding core communication methods in Go will elevate your skills. In this post, we'll cover:
- Standard HTTP servers for REST
- TCP sockets for low-level communication
- WebSocket for realtime data
- gRPC for efficient service communication
1. HTTP Server with net/http
Start with HTTP — the foundation of most web communication.
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, Golang HTTP!")
}
func main() {
http.HandleFunc("/", helloHandler)
http.ListenAndServe(":8080", nil)
}
Steps:
- Import
net/http - Create handler functions
- Use
http.HandleFuncto register routes - Run your server on port 8080
Test by visiting http://localhost:8080 in your browser.
2. TCP Socket Server with net package
Sockets provide lower-level, raw access to the network:
package main
import (
"fmt"
"net"
)
func main() {
ln, _ := net.Listen("tcp", ":9000")
for {
conn, _ := ln.Accept()
go func(c net.Conn) {
c.Write([]byte("Hello, TCP Client!\n"))
c.Close()
}(conn)
}
}
Steps:
- Listen on TCP port (e.g., 9000)
- Accept connections in a loop
- Write and close the connection
Connect to your server using telnet localhost 9000.
3. WebSocket Server with gorilla/websocket
Realtime applications often use WebSocket. Go's Gorilla WebSocket is a top choice.
Install:
go get github.com/gorilla/websocket
Example:
package main
import (
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{}
func wsHandler(w http.ResponseWriter, r *http.Request) {
conn, _ := upgrader.Upgrade(w, r, nil)
for {
mt, message, _ := conn.ReadMessage()
conn.WriteMessage(mt, message) // Echo
}
}
func main() {
http.HandleFunc("/ws", wsHandler)
http.ListenAndServe(":8081", nil)
}
Steps:
- Upgrade HTTP connection to WebSocket
- Echo messages between client/server
- Connect with a WebSocket client (e.g., browser or wscat)
4. gRPC Server
gRPC enables efficient communication in modern microservice architectures.
Prerequisites:
- Install Protocol Buffers compiler (
protoc) - Install Go gRPC packages
go get google.golang.org/grpc
go get google.golang.org/protobuf
Define a proto file (hello.proto):
syntax = "proto3";
service HelloService {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
Generate Go code:
protoc --go_out=. --go-grpc_out=. hello.proto
Minimal Server Example:
// Imports and generated code omitted for brevity
type server struct{}
func (s *server) SayHello(ctx context.Context, req *HelloRequest) (*HelloReply, error) {
return &HelloReply{Message: "Hello, " + req.Name}, nil
}
func main() {
grpcServer := grpc.NewServer()
RegisterHelloServiceServer(grpcServer, &server{})
lis, _ := net.Listen("tcp", ":50051")
grpcServer.Serve(lis)
}
Steps:
- Define protocol in
.protofile - Generate Go code via
protoc - Implement gRPC server and run on port 50051
Conclusion
Mastering these protocols makes you a flexible Go developer:
- Use HTTP for RESTful APIs
- Use sockets for custom protocols or raw data transfer
- Use WebSocket for realtime communication
- Use gRPC for high-performance RPC
Build, experiment, and extend as needed! Happy coding! 🚀
Top comments (0)