go-zero icon indicating copy to clipboard operation
go-zero copied to clipboard

How to implement global return of int64 id as string type

Open chemwol opened this issue 8 months ago • 3 comments

When using snowflake to generate int64 id, returning the id to the frontend may result in missing accuracy. How to implement global return of int64 id as string type

chemwol avatar May 06 '25 02:05 chemwol

maybe like this type Demo struct { ID int64 json:"id,string" }

Abei1uo avatar May 06 '25 05:05 Abei1uo

We need a global approach to handle it, there are too many interfaces

chemwol avatar May 06 '25 06:05 chemwol

Here's a simple approach:

1. Globally Customize JSON Serialization

  • Create a new type Int64String that wraps the int64 type.
  • Implement the MarshalJSON method to convert the int64 value into a string.
  • Use this custom type Int64String in your structs, and JSON serialization will automatically convert int64 to string.

2. Use Middleware to Modify Response

  • Use middleware to intercept HTTP responses before they are returned.
  • Parse the JSON response data.
  • Convert all int64 fields to strings.
  • Serialize the modified data back into JSON and return it.

Summary:

  • Approach 1: Customize JSON serialization for specific fields with a custom type.
  • Approach 2: Use middleware to intercept and modify the response JSON data.

zwell avatar May 06 '25 06:05 zwell