api

package
v0.7.11 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 17, 2026 License: MIT Imports: 12 Imported by: 11

README

REST API Utilities

This package aims to develop REST API in a standard way, and provides some utilities for unit test.

Initialize

It is highly recommended to initialize REST API service from a configuration file. Developers only are required to provide a factory to set up routers.

package main

import (
	"github.com/Conflux-Chain/go-conflux-util/api"
	"github.com/Conflux-Chain/go-conflux-util/api/middleware"
	"github.com/gin-gonic/gin"
)

func main() {
	// Setup routers
	factory := func(router *gin.Engine) {
		router.GET("/greeting", middleware.Wrap(someHandler))
	}

	// Start REST API server in a separate goroutine
	go api.MustServeFromViper(factory)

	select {}
}

func someHandler(c *gin.Context) (any, error) {
	return "hello world", nil
}

Uniform HTTP Response

This module provides common HTTP responses along with standard errors in JSON format.

type BusinessError struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    any         `json:"data"`
}

Code 0 indicates success, and Data is an object indicates the return value of REST API. Code with non-zero value indicates any error, and developers could refer to the Message and Data fields for more details.

Pre-defined Error Codes

There are some pre-defined errors as below:

  • 1: Invalid parameter.
  • 2: Internal server error.
  • 3: Too many requests.
  • 4: Database error.
  • 5: JWT error.

HTTP Response Status Code

To distinguish backend service error and gateway error, we only use 200 and 600 as HTTP response status code:

  • 200: success, or known business error, e.g. entity not found.
  • 600: unexpected system error, e.g. io error, encoding error.

Middlewares

There are some common used middlewares available:

  • JWT
  • Metrics
  • Wrapper to return (value, error) pair
  • Rate limit

Validators

There are some helpful validator tags available:

  • hex: starts with 0x prefix and contains an even number of hexadecimal characters, e.g. 0x, 0x12, 0x12abCD. The value could be decoded via hexutil.MustDecode(hexString), and it will never be panic.

Unit Test

Developers could easily write unit tests for all exported REST APIs based on the available test utilities. See examples below:

package foo

import (
	"testing"

	"github.com/Conflux-Chain/go-conflux-util/api/testutil"
	"github.com/gin-gonic/gin"
)

func newTestEngine() testutil.Engine {
	engine := gin.Default()

	// setup routers
	// setupRoutes(engine)

	return *testutil.NewEngine(engine)
}

type User struct {
	ID   string `json:"id" binding:"required"`
	Name string `json:"name" binding:"required"`
}

func TestFoo(t *testing.T) {
	engine := newTestEngine()

	engine.Post("/users").						// build post URL
		MustWithJSONBody(User{Name: "Alice"}).	// build JSON body
		AssertSuccess(t, uint64(1))				// assert new user ID is 1
}

Documentation

Index

Constants

View Source
const (
	ErrCodeSuccess         = 0
	ErrCodeValidation      = 1
	ErrCodeInternal        = 2
	ErrCodeTooManyRequests = 3
	ErrCodeDatabase        = 4
	ErrCodeJwt             = 5
)

Variables

View Source
var ErrNil = &BusinessError{ErrCodeSuccess, "Success", nil}

ErrNil is used for success response.

Functions

func MustServe

func MustServe(config Config, factory RouteFactory, mws ...middlewares.Middleware)

func MustServeFromViper

func MustServeFromViper(factory RouteFactory, middlewares ...middlewares.Middleware)

Types

type BusinessError

type BusinessError struct {
	// Code error code, 0 indicates success, otherwise business error (e.g. user not found) or internal server error.
	Code int `json:"code"`

	// Message error message associated with `Code`.
	Message string `json:"message"`

	// Data is the return value if success. Otherwise, it is concret failure reason in string type.
	Data any `json:"data"`
}

BusinessError is uniform data structure of REST API.

func ErrDatabase added in v0.6.1

func ErrDatabase(err error) *BusinessError

func ErrDatabaseCause added in v0.6.2

func ErrDatabaseCause(err error, cause string) *BusinessError

func ErrDatabaseCausef added in v0.6.2

func ErrDatabaseCausef(err error, cause string, args ...any) *BusinessError

func ErrInternal

func ErrInternal(err error) *BusinessError

func ErrJwt added in v0.6.5

func ErrJwt(cause string) *BusinessError

func ErrTooManyRequests

func ErrTooManyRequests(err error) *BusinessError

func ErrValidation

func ErrValidation(err error) *BusinessError

func ErrValidationStr added in v0.6.1

func ErrValidationStr(err string) *BusinessError

func ErrValidationStrf added in v0.6.2

func ErrValidationStrf(err string, args ...any) *BusinessError

func NewBusinessError

func NewBusinessError(code int, message string, data ...any) *BusinessError

func (*BusinessError) Error

func (err *BusinessError) Error() string

func (*BusinessError) WithData added in v0.6.0

func (err *BusinessError) WithData(data any) *BusinessError

type Config

type Config struct {
	Endpoint string `default:":12345"`

	RecoveryDisabled bool
	CorsOrigins      []string
	Logger           bool
}

type RouteFactory

type RouteFactory func(router *gin.Engine)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL