Skip to content

Instantly share code, notes, and snippets.

@Havoc24k
Last active April 22, 2022 21:43
Show Gist options
  • Save Havoc24k/f1d4a57af96234d0dcd9c453f621f36d to your computer and use it in GitHub Desktop.
Save Havoc24k/f1d4a57af96234d0dcd9c453f621f36d to your computer and use it in GitHub Desktop.
main.go
// Package main implements a server for Greeter service.
package main
import (
"context"
"flag"
"fmt"
"log"
"net"
"net/http"
"google.golang.org/grpc"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
"google.golang.org/grpc/reflection"
)
var (
port = flag.Int("port", 50051, "The server port")
)
// healthz
func healthz(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(200)
w.Write([]byte("ok"))
}
// server is used to implement helloworld.GreeterServer.
type server struct {
pb.UnimplementedGreeterServer
}
// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
log.Printf("Received: %v", in.GetName())
return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil
}
func main() {
flag.Parse()
lis, err := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", *port))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
// Healthz http server
go func() {
http.HandleFunc("/healthz", healthz)
http.ListenAndServe(":8080", nil)
}()
s := grpc.NewServer()
pb.RegisterGreeterServer(s, &server{})
// Register reflection service on gRPC server.
reflection.Register(s)
log.Printf("server listening at %v", lis.Addr())
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment