This lesson is locked. Login or Subscribe for more access!

Running a server correctly

Duration: 11 mins

Let's see how you can correctly run and shutdown a Go server.

Instructor

Chris Shepherd

Share with a friend!

Transcript

Hey folks, I thought I'd just do one more quick video to walk through how to run the server correctly. This is just so we can handle things like termination signals gracefully and also handle errors properly. Now, the solutions we've been using so far or the examples we've been using will work fine. As you've seen, the server will spin up and run, but the way we're handling errors is probably not the best way. We're also not gracefully shutting down or listening to the correct signals, so I thought it would be good to go over that as well.

So I've taken the example from the Hello World service that we've worked on before, and I'll walk through the main.go file to see how we can improve this. The first thing I would do is create a run function and extract everything into there. This allows us to propagate context, return errors properly, and test the function instead of having more logic in the main function. In the main function, we'll create a context using signal.NotifyContext, which cancels the context when specified signals are triggered.

We’ll pass os.Interrupt and os.Kill to the signal.NotifyContext function, so when the application receives one of these signals, the context cancels automatically. Using this cancellation, we can gracefully shut down our server. Adding a deferred call to cancel the context ensures everything is cleaned up properly when the application exits.

This setup also allows us to log errors effectively and return the correct exit code. For more complex applications, we might want to use a structured logging package like slog to make logs more informative and leveled. This approach makes it easier to debug and manage server behavior.