Heim Backend-Entwicklung Golang Erstellen einer RESTful-API mit Go Fibre: Ein von Express inspiriertes Boilerplate

Erstellen einer RESTful-API mit Go Fibre: Ein von Express inspiriertes Boilerplate

Oct 05, 2024 pm 04:07 PM

Building a RESTful API with Go Fiber: An Express-Inspired Boilerplate
A boilerplate/starter project for quickly building RESTful APIs using Go, Fiber, and PostgreSQL. Inspired by the Express boilerplate.

The app comes with many built-in features, such as authentication using JWT and Google OAuth2, request validation, unit and integration tests, docker support, API documentation, pagination, etc. For more details, check the features list below.

Table of Contents

  • Features
  • Commands
  • Environment Variables
  • Project Structure
  • API Documentation
  • Error Handling
  • Validation
  • Authentication
  • Authorization
  • Logging
  • Linting
  • Contributing

Features

  • SQL database: PostgreSQL Object Relation Mapping using Gorm
  • Database migrations: with golang-migrate
  • Validation: request data validation using Package validator
  • Logging: using Logrus and Fiber-Logger
  • Testing: unit and integration tests using Testify and formatted test output using gotestsum
  • Error handling: centralized error handling mechanism
  • API documentation: with Swag and Swagger
  • Sending email: using Gomail
  • Environment variables: using Viper
  • Security: set security HTTP headers using Fiber-Helmet
  • CORS: Cross-Origin Resource-Sharing enabled using Fiber-CORS
  • Compression: gzip compression with Fiber-Compress
  • Docker support
  • Linting: with golangci-lint

Commands

Clone the repo:


git clone --depth 1 https://github.com/indrayyana/go-fiber-boilerplate.git
cd go-fiber-boilerplate
rm -rf ./.git


Nach dem Login kopieren

Install the dependencies:


go mod tidy


Nach dem Login kopieren

Set the environment variables:


cp .env.example .env

# open .env and modify the environment variables (if needed)


Nach dem Login kopieren

Running locally:


make start


Nach dem Login kopieren

Or running with live reload:


air


Nach dem Login kopieren

Note:
Make sure you have Air installed.
See ? How to install Air

Testing:


# run all tests
make tests

# run all tests with gotestsum format
make testsum

# run test for the selected function name
make tests-TestUserModel


Nach dem Login kopieren

Docker:


# run docker container
make docker

# run all tests in a docker container
make docker-test


Nach dem Login kopieren

Linting:


# run lint
make lint


Nach dem Login kopieren

Swagger:


# generate the swagger documentation
make swagger


Nach dem Login kopieren

Migration:


# Create migration
make migration-<table-name>

# Example for table users
make migration-users


Nach dem Login kopieren

# run migration up in local
make migrate-up

# run migration down in local
make migrate-down

# run migration up in docker container
make migrate-docker-up

# run migration down all in docker container
make migrate-docker-down


Nach dem Login kopieren

Environment Variables

The environment variables can be found and modified in the .env file. They come with these default values:


# server configuration
# Env value : prod || dev
APP_ENV=dev
APP_HOST=0.0.0.0
APP_PORT=3000

# database configuration
DB_HOST=postgresdb
DB_USER=postgres
DB_PASSWORD=thisisasamplepassword
DB_NAME=fiberdb
DB_PORT=5432

# JWT
# JWT secret key
JWT_SECRET=thisisasamplesecret
# Number of minutes after which an access token expires
JWT_ACCESS_EXP_MINUTES=30
# Number of days after which a refresh token expires
JWT_REFRESH_EXP_DAYS=30
# Number of minutes after which a reset password token expires
JWT_RESET_PASSWORD_EXP_MINUTES=10
# Number of minutes after which a verify email token expires
JWT_VERIFY_EMAIL_EXP_MINUTES=10

# SMTP configuration options for the email service
SMTP_HOST=email-server
SMTP_PORT=587
SMTP_USERNAME=email-server-username
SMTP_PASSWORD=email-server-password
EMAIL_FROM=support@yourapp.com

# OAuth2 configuration
GOOGLE_CLIENT_ID=yourapps.googleusercontent.com
GOOGLE_CLIENT_SECRET=thisisasamplesecret
REDIRECT_URL=http://localhost:3000/v1/auth/google-callback


Nach dem Login kopieren

Project Structure


src\
 |--config\         # Environment variables and configuration related things
 |--controller\     # Route controllers (controller layer)
 |--database\       # Database connection & migrations
 |--docs\           # Swagger files
 |--middleware\     # Custom fiber middlewares
 |--model\          # Postgres models (data layer)
 |--response\       # Response models
 |--router\         # Routes
 |--service\        # Business logic (service layer)
 |--utils\          # Utility classes and functions
 |--validation\     # Request data validation schemas
 |--main.go         # Fiber app


Nach dem Login kopieren

API Documentation

To view the list of available APIs and their specifications, run the server and go to http://localhost:3000/v1/docs in your browser.

Building a RESTful API with Go Fiber: An Express-Inspired Boilerplate

Building a RESTful API with Go Fiber: An Express-Inspired Boilerplate

This documentation page is automatically generated using the Swag definitions written as comments in the controller files.

See ? Declarative Comments Format.

API Endpoints

List of available routes:

Auth routes:\
POST /v1/auth/register - register\
POST /v1/auth/login - login\
POST /v1/auth/logout - logout\
POST /v1/auth/refresh-tokens - refresh auth tokens\
POST /v1/auth/forgot-password - send reset password email\
POST /v1/auth/reset-password - reset password\
POST /v1/auth/send-verification-email - send verification email\
POST /v1/auth/verify-email - verify email\
GET /v1/auth/google - login with google account

User routes:\
POST /v1/users - create a user\
GET /v1/users - get all users\
GET /v1/users/:userId - get user\
PATCH /v1/users/:userId - update user\
DELETE /v1/users/:userId - delete user

Error Handling

The app includes a custom error handling mechanism, which can be found in the src/utils/error.go file.

It also utilizes the Fiber-Recover middleware to gracefully recover from any panic that might occur in the handler stack, preventing the app from crashing unexpectedly.

The error handling process sends an error response in the following format:


{
  "code": 404,
  "status": "error",
  "message": "Not found"
}


Nach dem Login kopieren

Fiber provides a custom error struct using fiber.NewError(), where you can specify a response code and a message. This error can then be returned from any part of your code, and Fiber's ErrorHandler will automatically catch it.

For example, if you are trying to retrieve a user from the database but the user is not found, and you want to return a 404 error, the code might look like this:


func (s *userService) GetUserByID(c *fiber.Ctx, id string) {
    user := new(model.User)

    err := s.DB.WithContext(c.Context()).First(user, "id = ?", id).Error

    if errors.Is(err, gorm.ErrRecordNotFound) {
        return fiber.NewError(fiber.StatusNotFound, "User not found")
    }
}


Nach dem Login kopieren

Validation

Request data is validated using Package validator. Check the documentation for more details on how to write validations.

The validation schemas are defined in the src/validation directory and are used within the services by passing them to the validation logic. In this example, the CreateUser method in the userService uses the validation.CreateUser schema to validate incoming request data before processing it. The validation is handled by the Validate.Struct method, which checks the request data against the schema.


import (
    "app/src/model"
    "app/src/validation"

    "github.com/gofiber/fiber/v2"
)

func (s *userService) CreateUser(c *fiber.Ctx, req validation.CreateUser) (*model.User, error) {
    if err := s.Validate.Struct(&req); err != nil {
        return nil, err
    }
}


Nach dem Login kopieren

Authentication

To require authentication for certain routes, you can use the Auth middleware.


import (
    "app/src/controllers"
    m "app/src/middleware"
    "app/src/services"

    "github.com/gofiber/fiber/v2"
)

func SetupRoutes(app *fiber.App, u services.UserService, t services.TokenService) {
  userController := controllers.NewUserController(u, t)
    app.Post("/users", m.Auth(u), userController.CreateUser)
}


Nach dem Login kopieren

These routes require a valid JWT access token in the Authorization request header using the Bearer schema. If the request does not contain a valid access token, an Unauthorized (401) error is thrown.

Generating Access Tokens:

An access token can be generated by making a successful call to the register (POST /v1/auth/register) or login (POST /v1/auth/login) endpoints. The response of these endpoints also contains refresh tokens (explained below).

An access token is valid for 30 minutes. You can modify this expiration time by changing the JWT_ACCESS_EXP_MINUTES environment variable in the .env file.

Refreshing Access Tokens:

After the access token expires, a new access token can be generated, by making a call to the refresh token endpoint (POST /v1/auth/refresh-tokens) and sending along a valid refresh token in the request body. This call returns a new access token and a new refresh token.

A refresh token is valid for 30 days. You can modify this expiration time by changing the JWT_REFRESH_EXP_DAYS environment variable in the .env file.

Authorization

The Auth middleware can also be used to require certain rights/permissions to access a route.


import (
    "app/src/controllers"
    m "app/src/middleware"
    "app/src/services"

    "github.com/gofiber/fiber/v2"
)

func SetupRoutes(app *fiber.App, u services.UserService, t services.TokenService) {
  userController := controllers.NewUserController(u, t)
    app.Post("/users", m.Auth(u, "manageUsers"), userController.CreateUser)
}


Nach dem Login kopieren

In the example above, an authenticated user can access this route only if that user has the manageUsers permission.

The permissions are role-based. You can view the permissions/rights of each role in the src/config/roles.go file.

If the user making the request does not have the required permissions to access this route, a Forbidden (403) error is thrown.

Logging

Import the logger from src/utils/logrus.go. It is using the Logrus logging library.

Logging should be done according to the following severity levels (ascending order from most important to least important):


import "app/src/utils"

utils.Log.Panic('message') // Calls panic() after logging
utils.Log.Fatal('message'); // Calls os.Exit(1) after logging
utils.Log.Error('message');
utils.Log.Warn('message');
utils.Log.Info('message');
utils.Log.Debug('message');
utils.Log.Trace('message');


Nach dem Login kopieren

Note:
API request information (request url, response code, timestamp, etc.) are also automatically logged (using Fiber-Logger).

Linting

Linting is done using golangci-lint

See ? How to install golangci-lint

To modify the golangci-lint configuration, update the .golangci.yml file.

Contributing

Contributions are more than welcome! Please check out the contributing guide.

If you find this boilerplate useful, consider giving it a star! ⭐

The full source code is available at the GitHub link below:

https://github.com/indrayyana/go-fiber-boilerplate

Das obige ist der detaillierte Inhalt vonErstellen einer RESTful-API mit Go Fibre: Ein von Express inspiriertes Boilerplate. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn

Heiße KI -Werkzeuge

Undresser.AI Undress

Undresser.AI Undress

KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover

AI Clothes Remover

Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool

Undress AI Tool

Ausziehbilder kostenlos

Clothoff.io

Clothoff.io

KI-Kleiderentferner

Video Face Swap

Video Face Swap

Tauschen Sie Gesichter in jedem Video mühelos mit unserem völlig kostenlosen KI-Gesichtstausch-Tool aus!

Heiße Werkzeuge

Notepad++7.3.1

Notepad++7.3.1

Einfach zu bedienender und kostenloser Code-Editor

SublimeText3 chinesische Version

SublimeText3 chinesische Version

Chinesische Version, sehr einfach zu bedienen

Senden Sie Studio 13.0.1

Senden Sie Studio 13.0.1

Leistungsstarke integrierte PHP-Entwicklungsumgebung

Dreamweaver CS6

Dreamweaver CS6

Visuelle Webentwicklungstools

SublimeText3 Mac-Version

SublimeText3 Mac-Version

Codebearbeitungssoftware auf Gottesniveau (SublimeText3)

Heiße Themen

Java-Tutorial
1657
14
PHP-Tutorial
1257
29
C#-Tutorial
1229
24
Golangs Zweck: Aufbau effizienter und skalierbarer Systeme Golangs Zweck: Aufbau effizienter und skalierbarer Systeme Apr 09, 2025 pm 05:17 PM

Go Language funktioniert gut beim Aufbau effizienter und skalierbarer Systeme. Zu den Vorteilen gehören: 1. hohe Leistung: Kompiliert in den Maschinencode, schnelle Laufgeschwindigkeit; 2. gleichzeitige Programmierung: Vereinfachen Sie Multitasking durch Goroutinen und Kanäle; 3. Einfachheit: präzise Syntax, Reduzierung der Lern- und Wartungskosten; 4. plattform: Unterstützt die plattformübergreifende Kompilierung, einfache Bereitstellung.

Golang und C: Parallelität gegen Rohgeschwindigkeit Golang und C: Parallelität gegen Rohgeschwindigkeit Apr 21, 2025 am 12:16 AM

Golang ist in Gleichzeitigkeit besser als C, während C bei Rohgeschwindigkeit besser als Golang ist. 1) Golang erreicht durch Goroutine und Kanal eine effiziente Parallelität, die zum Umgang mit einer großen Anzahl von gleichzeitigen Aufgaben geeignet ist. 2) C über Compiler -Optimierung und Standardbibliothek bietet es eine hohe Leistung in der Nähe der Hardware, die für Anwendungen geeignet ist, die eine extreme Optimierung erfordern.

Golang gegen Python: Schlüsselunterschiede und Ähnlichkeiten Golang gegen Python: Schlüsselunterschiede und Ähnlichkeiten Apr 17, 2025 am 12:15 AM

Golang und Python haben jeweils ihre eigenen Vorteile: Golang ist für hohe Leistung und gleichzeitige Programmierung geeignet, während Python für Datenwissenschaft und Webentwicklung geeignet ist. Golang ist bekannt für sein Parallelitätsmodell und seine effiziente Leistung, während Python für sein Ökosystem für die kurze Syntax und sein reiches Bibliothek bekannt ist.

Golang gegen Python: Leistung und Skalierbarkeit Golang gegen Python: Leistung und Skalierbarkeit Apr 19, 2025 am 12:18 AM

Golang ist in Bezug auf Leistung und Skalierbarkeit besser als Python. 1) Golangs Kompilierungseigenschaften und effizientes Parallelitätsmodell machen es in hohen Parallelitätsszenarien gut ab. 2) Python wird als interpretierte Sprache langsam ausgeführt, kann aber die Leistung durch Tools wie Cython optimieren.

Das Performance -Rennen: Golang gegen C. Das Performance -Rennen: Golang gegen C. Apr 16, 2025 am 12:07 AM

Golang und C haben jeweils ihre eigenen Vorteile bei Leistungswettbewerben: 1) Golang ist für eine hohe Parallelität und schnelle Entwicklung geeignet, und 2) C bietet eine höhere Leistung und eine feinkörnige Kontrolle. Die Auswahl sollte auf Projektanforderungen und Teamtechnologie -Stack basieren.

C und Golang: Wenn die Leistung von entscheidender Bedeutung ist C und Golang: Wenn die Leistung von entscheidender Bedeutung ist Apr 13, 2025 am 12:11 AM

C eignet sich besser für Szenarien, in denen eine direkte Kontrolle der Hardware -Ressourcen und hohe Leistungsoptimierung erforderlich ist, während Golang besser für Szenarien geeignet ist, in denen eine schnelle Entwicklung und eine hohe Parallelitätsverarbeitung erforderlich sind. 1.Cs Vorteil liegt in den nahezu Hardware-Eigenschaften und hohen Optimierungsfunktionen, die für leistungsstarke Bedürfnisse wie die Spieleentwicklung geeignet sind. 2. Golangs Vorteil liegt in seiner präzisen Syntax und der natürlichen Unterstützung, die für die Entwicklung einer hohen Parallelitätsdienste geeignet ist.

Golangs Auswirkungen: Geschwindigkeit, Effizienz und Einfachheit Golangs Auswirkungen: Geschwindigkeit, Effizienz und Einfachheit Apr 14, 2025 am 12:11 AM

GoimpactsDevelopmentPositivyThroughSpeed, Effizienz und DiasMlitication.1) Geschwindigkeit: Gocompilesquickandrunseffiction, idealforlargeProjects

Golang und C: Die Kompromisse bei der Leistung Golang und C: Die Kompromisse bei der Leistung Apr 17, 2025 am 12:18 AM

Die Leistungsunterschiede zwischen Golang und C spiegeln sich hauptsächlich in der Speicherverwaltung, der Kompilierungsoptimierung und der Laufzeiteffizienz wider. 1) Golangs Müllsammlung Mechanismus ist praktisch, kann jedoch die Leistung beeinflussen.

See all articles