Simplify Go Microservices to RESTful APIs with Ginrest and Generics

This article introduces Ginrest, a Go 1.18 generic‑based library that streamlines the conversion of gRPC or other microservice functions into RESTful endpoints by providing request/response wrappers, unified error handling, and context utilities, dramatically reducing repetitive boilerplate code.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Simplify Go Microservices to RESTful APIs with Ginrest and Generics

Background

In a microservice or service‑oriented architecture, most business‑logic functions are written as long gRPC handlers such as:

func (s *Service) GetUserInfo(ctx context.Context, req *pb.GetUserInfoReq) (*pb.GetUserInfoRsp, error) {
    // business logic
    // ...
}

The client side looks similar:

func (s *Service) GetUserInfo(ctx context.Context, req *pb.GetUserInfoReq, opts ...grpc.CallOption) (*pb.GetUserInfoRsp, error) {
    // business logic
    // ...
}

When exposing these services as RESTful APIs, developers repeatedly write code for HTTP method, URL, authentication, parameter binding, request handling and response handling.

Why Ginrest?

Ginrest is a lightweight Go library that uses Go 1.18 generics to eliminate the repetitive boilerplate. It is not a full‑featured framework, but a set of helpers that wrap the common patterns.

Features

Encapsulate RESTful request and response with a standard Rsp{code, msg, data} format.

Unified numeric error codes ([0, 4XXX, 5XXX]) and error struct Error{code, msg}.

Recovery middleware that returns a consistent panic response.

Context helpers SetKey() and GetKey() for storing generic values. ReqFunc() to populate request structs.

Usage Example

Define error codes, request/response structs and service functions:

const (
    ErrCodeUserNotExists = 40100 // user does not exist
)

type GetUserInfoReq struct {
    UID int `json:"uid"`
}

type GetUserInfoRsp struct {
    UID      int    `json:"uid"`
    Username string `json:"username"`
    Age      int    `json:"age"`
}

func GetUserInfo(ctx context.Context, req *GetUserInfoReq) (*GetUserInfoRsp, error) {
    if req.UID != 10 {
        return nil, ginrest.NewError(ErrCodeUserNotExists, "user not exists")
    }
    return &GetUserInfoRsp{UID: req.UID, Username: "user_10", Age: 10}, nil
}

// UpdateUserInfo implementation omitted for brevity

Register routes with Gin and Ginrest:

func main() {
    e := gin.New()
    e.Use(ginrest.Recovery())
    Register(e)
    if err := e.Run("127.0.0.1:8000"); err != nil {
        log.Println(err)
    }
}

func Register(e *gin.Engine) {
    e.GET("/user/info/get", ginrest.Do(nil, GetUserInfo))
    reqFunc := func(c *gin.Context, req *UpdateUserInfoReq) {
        req.UID = GetUID(c)
    }
    e.POST("/user/info/update", Verify, ginrest.Do(reqFunc, UpdateUserInfo))
}

Running the program and sending HTTP requests yields responses such as:

GET /user/info/get
{ "uid": 10 }
Response:
{ "code": 0, "msg": "ok", "data": { "uid": 10, "username": "user_10", "age": 10 } }

Implementation Details

The public Do() and DoOpt() functions delegate to a generic do[Req any, Rsp any, Opt any] helper that performs:

JSON binding with BindJSON[Req].

Optional request‑side processing via a ReqFunc.

Invocation of the service function or an optional service‑option function.

Response handling through ProcessRsp, which calls Success or Failure based on the error.

Additional helpers include BindJSON, ProcessRsp, Success, Failure, and the error type Error with constructors like NewError.

Conclusion

If the library does not match a specific project’s needs, developers can follow the same pattern to create a custom wrapper that unifies request and response handling, dramatically reducing boilerplate code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

GoRESTfulGin
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.