Building and Testing a REST API in Go with Gorilla Mux and PostgreSQL

This tutorial will illustrate how you can build a REST API backed by PostgreSQL in Go, using Gorilla Mux for routing. The tutorial will employ test-driven development and will conclude by explaining how you can continuously test against a database during development.

Thank you for your nice article. I have implemented my tests and locally it works to some extent.

Now I found, that it has issues report always port is already in use regardless which port I am using. Sequence is dead simple and it is implemented like you recommended:

Testmain

a = App{}
err := a.Initialize()
if err != nil {
log.Fatal(err)
}
err = a.Run(":8085")
if err != nil {
log.Fatal(err)
}

app.go

// Initialize app
func (a *App) Initialize() error {
_, callPath, _, _ := runtime.Caller(0)
projectRoot := filepath.Join(filepath.Dir(callPath), “…/”)
logger.InitLogger(projectRoot, “xyz-srv.log”)
err := configurationloader.LoadConfig()
if err != nil {
return err
}
a.Router, err = router.CreateRouter()
if err != nil {
return err
}
return nil
}

// Run the hosted pages service on given address
func (a *App) Run(addr string) error {
return http.ListenAndServe(addr, a.Router)
}

Do you have faced same issues or any other ideas how to solve?
thank you.
Thomas

How do I run the app.
I’ve tried to use go run main.go and i’m getting an error saying ‘undefined: App’. Help me out ASAP please

1 Like

had the same issue. you probably did a go run main.go . this won’t recognize packages imported.
try running
go build
and then just run your executable. i named my module “templates” so go build created an executable file named templates.exe so i ran templates.exe on my terminal and server started.
need to get in the habit of running go build and then running executable instead of just go run for starting a server. go run is mainly for just running a test files

Thank you for reporting this issue. I think the problem might be that Go modules have not been initialized. You can try running:

export GO111MODULE=on
export GOFLAGS=-mod=vendor
go mod vendor

Before attempting to run the application.

I’ve updated the blog post with a more detailed explanation of the process. You can also find the complete code of the demo in this repository:

Let me know if you have any issues. Thanks

Tomas