-2

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?

JackH
  • 4,613
  • 4
  • 36
  • 61
  • 5
    You can start as many servers as you want, but both of your `start*` functions are blocking, so you'll need to run them both in separate goroutines (and keep `main` from returning early, typically by waiting on a signal like `SIGTERM`). – Adrian Apr 05 '21 at 15:37
  • 1
    Change `startGRPCServer()` to [`go startGRPCServer()`](https://golang.org/ref/spec#Go_statements) and keep the rest as is. – mkopriva Apr 05 '21 at 15:46

1 Answers1

4

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)
        }
    }()
}
Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242