Welcome back! In Part 1, we set up our project structure and created a basic Makefile. In this part, we’ll dive into coding and start setting up our Golang API using the packages we discussed.
Setting Up the Configuration
First, let's create a configuration file to manage our environment variables. Create a .env
file in the root of your project with the following content:
APP_SCREET=app_screet
APP_PORT=3000
DB_DRIVER=postgres
DB_HOST=localhost
DB_NAME=dbname
DB_USER=postgres
DB_PASSWORD=postgres
DB_PORT=5432
Now, create config/config.go
to load these environment variables:
package config
import (
"fmt"
"os"
"github.com/joho/godotenv"
)
func Config(key string) string {
err := godotenv.Load(".env")
if err != nil {
fmt.Print("Error loading .env file")
}
return os.Getenv(key)
}
Setting Up the Fiber Framework
Let's set up our main entry point. Create main.go:
package main
import (
"log"
"your_project/config"
"your_project/router"
"github.com/gofiber/fiber/v2"
)
func main() {
secret := config.Config("APP_SECRET")
if secret == "" {
log.Panic("You must generate the secret key first")
}
app := fiber.New()
port := config.Config("APP_PORT")
router.SetupRouter(app)
if err := app.Listen(":" + port); err != nil {
log.Panic("Server won't run: ", err.Error())
}
}
Setting Up the Router
Now, let's create the router. Create router/router.go
:
package router
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
)
func SetupRouter(app *fiber.App) {
app.Use(cors.New())
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, World!")
})
}
Yay!! 🎉 now we've done to set up the main function of the API, let's try to run it using make command
make watch
This will start the Fiber server, and you can now access your API at http://localhost:3000/
Next Steps
In the next part of this series, we’ll enhance our boilerplate by adding JWT-based authentication and middleware. We’ll also cover how to connect to the database and create the migration file.
Stay tuned for Part 3!
Top comments (0)