From f82174ff7ba73d438ffb3c5403ab7baf59d2512d Mon Sep 17 00:00:00 2001 From: Sanskarzz Date: Wed, 13 Mar 2024 17:32:59 +0530 Subject: [PATCH] perf: added http and grpc server in diff goroutines Signed-off-by: Sanskarzz --- main.go | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/main.go b/main.go index 5be47c33..3d77c55c 100644 --- a/main.go +++ b/main.go @@ -9,37 +9,49 @@ import ( "google.golang.org/grpc" ) -func startHTTPserver() { - http.HandleFunc("/", handler) +type Servers struct { + httpServer *http.Server + grpcServer *grpc.Server +} - err := http.ListenAndServe(":8080", nil) - if err != nil { - log.Fatal("ListenAndServe: ", err) +func NewServers() *Servers { + return &Servers{} +} + +func (s *Servers) startHTTPServer() { + + s.httpServer = &http.Server{ + Addr: ":8080", + Handler: http.HandlerFunc(handler), } fmt.Println("Starting HTTP server on Port 8080") + if err := s.httpServer.ListenAndServe(); err != nil { + log.Fatal("ListenAndServe: ", err) + } } func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello World!") } -func startGRPCServer() { +func (s *Servers) startGRPCServer() { lis, err := net.Listen("tcp", ":9090") if err != nil { log.Fatalf("failed to listen: %v", err) } - grpcServer := grpc.NewServer() + s.grpcServer = grpc.NewServer() fmt.Println("Starting GRPC server on Port 9090") - if err := grpcServer.Serve(lis); err != nil { + if err := s.grpcServer.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } - } func main() { - startHTTPserver() - startGRPCServer() + srv := NewServers() + go srv.startHTTPServer() + go srv.startGRPCServer() + select {} }