Implementing the Transport Package Image Implementing the Transport Package

Implementing the Transport Package

February 6, 2021

Course Instructor: Elliot Forbes

Hey Gophers! My name is Elliot and I'm the creator of TutorialEdge and I've been working with Go systems for roughly 5 years now. Feel free to reach out to me on twitter - @Elliot_F

So, we have our basic app structure defined, let’s start looking at how we can build out the server aspect and start serving some basic endpoints.

Now that we have some idea as to how we can structure our app, it’s time to dive in and start fleshing out some of the basic functionality.

The first endpoint we’ll want to build is a simple health check endpoint that simply returns a status 200 OK if the service is up and healthy. Health checks are important in applications and, if done correctly can quickly return the operational health of your systems and alert you when things go bad.

To do this, we’ll need to set up the base for a http service. We’ll want to do this within a transport package and then we can call into this package from our main.go file in order to setup the routes etc.

Let’s create a new file now called internal/transport/http.go in which we’ll do the following:

package http

import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
)

// Handler - stores pointer to our comments service
type Handler struct {
	Router *mux.Router
}

// NewHandler - returns a pointer to a Handler
func NewHandler() *Handler {
	return &Handler{}
}

// SetupRoutes - sets up all the routes for our application
func (h *Handler) SetupRoutes() {
	fmt.Println("Setting Up Routes")
	h.Router = mux.NewRouter()
	h.Router.HandleFunc("/api/health", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "I am alive!")
	})
}

Finally, with this in place, we now want to update our main.go file so that it first imports this new transport/http package from within our project and then we’ll want it to call SetupRoutes for us.

package main

import (
	"fmt"
	"net/http"

	transportHTTP "github.com/TutorialEdge/go-rest-api-course/internal/transport/http"
)

// App - the struct which contains things like pointers
// to database connections
type App struct{}

// Run - sets up our application
func (app *App) Run() error {
	fmt.Println("Setting Up Our APP")

	handler := transportHTTP.NewHandler()
	handler.SetupRoutes()

	if err := http.ListenAndServe(":8080", handler.Router); err != nil {
		fmt.Println("Failed to set up server")
		return err
	}

	return nil
}

func main() {
	fmt.Println("Go REST API Course")
	app := App{}
	if err := app.Run(); err != nil {
		fmt.Println("Error starting up our REST API")
		fmt.Println(err)
	}
}