go-zero
go-zero copied to clipboard
How to implement global return of int64 id as string type
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
maybe like this
type Demo struct {
ID int64 json:"id,string"
}
We need a global approach to handle it, there are too many interfaces
Here's a simple approach:
1. Globally Customize JSON Serialization
- Create a new type
Int64Stringthat wraps theint64type. - Implement the
MarshalJSONmethod to convert theint64value into a string. - Use this custom type
Int64Stringin your structs, and JSON serialization will automatically convertint64to string.
2. Use Middleware to Modify Response
- Use middleware to intercept HTTP responses before they are returned.
- Parse the JSON response data.
- Convert all
int64fields 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.