찾다
백엔드 개발GolangGo Fiber를 사용하여 RESTful API 구축: Express에서 영감을 받은 상용구

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


Install the dependencies:


go mod tidy


Set the environment variables:


cp .env.example .env

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


Running locally:


make start


Or running with live reload:


air


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


Docker:


# run docker container
make docker

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


Linting:


# run lint
make lint


Swagger:


# generate the swagger documentation
make swagger


Migration:


# Create migration
make migration-<table-name>

# Example for table users
make migration-users


</table-name>

# 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


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


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


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"
}


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")
    }
}


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
    }
}


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)
}


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)
}


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');


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

위 내용은 Go Fiber를 사용하여 RESTful API 구축: Express에서 영감을 받은 상용구의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이동 중에 시작 함수에 의존하는 테스트 코드이동 중에 시작 함수에 의존하는 테스트 코드May 03, 2025 am 12:20 AM

WhentestinggocodewithInitFunctions, useExplicitSetUpFunctionsOrsParateTestOvoiddenceNInItfictionSideffects.1) useExplicitSetUpFunctoControlGlobalVariableInitialization.2) CreateSeparateTesteSpilestobySinitFunctions 및 testesten

GO의 오류 처리 방식을 다른 언어와 비교합니다GO의 오류 처리 방식을 다른 언어와 비교합니다May 03, 2025 am 12:20 AM

go'serrorhandlingreturnserrorsvalues ​​whithuseexceptions와 달리 1) Go'sMethodensuresexpliciterRorhandling, promotingrobustcodebutincreasingverbosity.2) Javaandthon'sexextionslowercodebutcodebutcodebutcanlederforlortorifneterfortorifneteriflerortorifnetrorirederiflofertorifneateRoferfortoriflogertoflortoflerortofneateRofer

효과적인 인터페이스 설계를위한 모범 사례효과적인 인터페이스 설계를위한 모범 사례May 03, 2025 am 12:18 AM

AneffectiveInterfaceingoisminimal, Clear, and Promotesloosecoupling.1) Minimizetheinterfaceforflexibilityandeasofimplementation.2) usicfacesforabStractionToswapimementationswhangingCallingCode.3) DesignStabilitySUsingInterfacestomockDep

중앙 집중식 오류 처리 전략중앙 집중식 오류 처리 전략May 03, 2025 am 12:17 AM

중앙 집중식 오류 처리는 GO 언어에서 코드의 가독성과 유지 가능성을 향상시킬 수 있습니다. 구현 방법 및 장점에는 다음이 포함됩니다. 1. 비즈니스 로직에서 별도의 오류 처리 로직 및 코드를 단순화합니다. 2. 중앙 처리로 오류 처리의 일관성을 확인하십시오. 3. 연기 및 복구를 사용하여 공황을 포착하고 처리하여 프로그램 견고성을 향상시킵니다.

GO에서 패키지 초기화를위한 시작 함수를위한 대안GO에서 패키지 초기화를위한 시작 함수를위한 대안May 03, 2025 am 12:17 AM

Ingo, alternativestoinitFunctionsincustomInitializationFenctionsandsingletons.1) CustomInitializationFunctionsallowExplicitControlover wheninInitializationOccurs, lexplodElayEdorConditionalSetUps.2) SingletEntensureOne-TimeInitializationIncOncurrent

GO 인터페이스로 어설 션 및 유형 스위치를 입력하십시오GO 인터페이스로 어설 션 및 유형 스위치를 입력하십시오May 02, 2025 am 12:20 AM

gohandlesinterfacesandtypeassertionsefectively, codeflexibleandrobustness.1) typeSertionsOncaLownallowRuntImeTypeChecking, asseengehapeInterfaceAndCircLetype.2) TypeStwitchEshandleMultipleTypesePesePesePesePesePese -pervariousShapesimplementing Gry

오류를 사용하고 오류가 발생합니다. 오류 검사는 이동 중입니다오류를 사용하고 오류가 발생합니다. 오류 검사는 이동 중입니다May 02, 2025 am 12:11 AM

GO 언어 오류 처리는 오류와 오류를 통해 더욱 유연하고 읽을 수 있습니다. 1.Errors.is는 오류가 지정된 오류와 동일한 지 확인하는 데 사용되며 오류 체인의 처리에 적합합니다. 2. 오류. 오류 유형을 확인할 수있을뿐만 아니라 오류를 특정 유형으로 변환 할 수 있으며 오류 정보 추출에 편리합니다. 이러한 기능을 사용하면 오류 처리 로직을 단순화 할 수 있지만 오류 체인의 올바른 전달에주의를 기울이고 코드 복잡성을 방지하기 위해 과도한 의존성을 피하십시오.

GO의 성능 튜닝 : 응용 프로그램 최적화GO의 성능 튜닝 : 응용 프로그램 최적화May 02, 2025 am 12:06 AM

TomakeGoApplicationSRUNFASTERONDERFISTING, 사용 프로파일 링 툴, leverageConcurrency, andManageMemoryEffice.1) usepprofforcpuandMemoryProfingToIndifyBottLenecks.2) UtizeGoroutinesandChannelStoparAllelizetAskSandimProvePercormance.3) 3)

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.