-
Notifications
You must be signed in to change notification settings - Fork 144
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
docs: 添加「如何控制 http 返回 enum(枚举类型)的名称和数字」 (#194)
* docs: 添加「如何控制 http 返回 enum(枚举类型)的名称和数字」 * docs: add en documentation
- Loading branch information
1 parent
d590ec8
commit 041e086
Showing
2 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -81,3 +81,24 @@ func init() { | |
} | ||
``` | ||
|
||
### 11、控制 http 返回 enum(枚举类型)的名称和数字 | ||
|
||
可以在http服务的main.go中引入 | ||
``` | ||
import ( | ||
"github.com/go-kratos/kratos/v2/encoding/json" | ||
"google.golang.org/protobuf/encoding/protojson" | ||
) | ||
``` | ||
在init方法中设置json.MarshalOptions | ||
``` | ||
func init() { | ||
... | ||
//增加这段代码 | ||
json.MarshalOptions = protojson.MarshalOptions{ | ||
UseEnumNumbers: true, // 将枚举值作为数字发出,默认为枚举值的字符串 | ||
} | ||
} | ||
``` | ||
|
||
更多控制 http 返回内容,请参考文档:https://pkg.go.dev/google.golang.org/[email protected]/encoding/protojson#MarshalOptions |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -81,8 +81,30 @@ func init() { | |
} | ||
``` | ||
|
||
### 11、Controls the name and number of the enum (enumeration type) returned by http | ||
|
||
You can import it in the `main.go` of the http service | ||
|
||
``` | ||
import ( | ||
"github.com/go-kratos/kratos/v2/encoding/json" | ||
"google.golang.org/protobuf/encoding/protojson" | ||
) | ||
``` | ||
|
||
Set `json.MarshalOptions` in the init method | ||
|
||
``` | ||
func init() { | ||
flag.StringVar(&flagconf, "conf", "../../configs", "config path, eg: -conf config.yaml") | ||
// Add this code | ||
json.MarshalOptions = protojson.MarshalOptions{ | ||
UseEnumNumbers: true, // UseEnumNumbers emits enum values as numbers. | ||
} | ||
} | ||
``` | ||
|
||
For more control over http return content, please refer to the documentation: https://pkg.go.dev/google.golang.org/[email protected]/encoding/protojson#MarshalOptions | ||
|
||
|
||
|