Search code examples
gogo-gingrpc-go

Why can't I start two servers in the same Go project?


I am a new Go developer and I am trying to build a single project that has both a gRPC server and a Gin HTTP server. This is what my code roughly looks like:

package main

import (
    "log"
    "net"

    "github.com/gin-gonic/gin"
    "google.golang.org/grpc"
)

func main() {
    startGRPCServer()
    startHTTPServer()
}

func startGRPCServer() {
    listener, err := net.Listen("tcp", ":9000")
    if err != nil {
        log.Fatalf("could not attach listener to port: %v", err)
    }

    s := grpc.NewServer()
    if err := s.Serve(listener); err != nil {
        log.Fatalf("could not start grpc server: %v", err)
    }
}

func startHTTPServer() {
    g := gin.Default()

    if err := g.Run(":8000"); err != nil {
        log.Fatalf("could not start http server: %v", err)
    }
}

When I run the code above, only the gRPC server starts. The startHTTPServer() function doesn't even get invoked. When I switch the order of the calls (move startHTTPServer() above startGRPCServer()), the startGRPCServer() function never gets called. Why does this happen? How can I fix this so that both functions get called and both servers run?


Solution

  • The startGRPCServer function blocks on running the grpc server. Run the GRPC server in a goroutine so that startGRPCServer returns.

    func startGRPCServer() {
        listener, err := net.Listen("tcp", ":9000")
        if err != nil {
            log.Fatalf("could not attach listener to port: %v", err)
        }
    
        s := grpc.NewServer()
        go func() {
            if err := s.Serve(listener); err != nil {
                log.Fatalf("could not start grpc server: %v", err)
            }
        }()
    }