Skip to content

Commit 4383314

Browse files
Improve import compatibility for sonic and jsoniter (#86)
* Improve import compatibility for sonic and jsoniter * fix import (#87) --------- Co-authored-by: Alex - アレックス <[email protected]>
1 parent 7908e12 commit 4383314

File tree

6 files changed

+43
-33
lines changed

6 files changed

+43
-33
lines changed

_examples/golang-basics/example.gen.go

Lines changed: 17 additions & 16 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

_examples/golang-basics/example.ridl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ struct Version
7373

7474
struct ComplexType
7575
- meta: map<string,any>
76+
+ go.field.type = json.RawMessage
7677
- metaNestedExample: map<string,map<string,uint32>>
7778
- namesList: []string
7879
- numsList: []int64

client.go.tmpl

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
{{- $typeMap := .TypeMap -}}
33
{{- $typePrefix := .TypePrefix -}}
44
{{- $services := .Services -}}
5+
{{- $json := .Json -}}
56
{{- $opts := .Opts }}
67

78
{{- if $services -}}
@@ -155,7 +156,7 @@ func (r *streamReader) read(v interface {}) error {
155156
continue
156157
}
157158

158-
if err := json.Unmarshal(line, &v); err != nil {
159+
if err := {{$json}}.Unmarshal(line, &v); err != nil {
159160
return r.handleReadError(err)
160161
}
161162
return nil
@@ -223,7 +224,7 @@ func newRequest(ctx context.Context, url string, reqBody io.Reader, contentType
223224

224225
// doHTTPRequest is common code to make a request to the remote service.
225226
func doHTTPRequest(ctx context.Context, client HTTPClient, url string, in, out interface{}) (*http.Response, error) {
226-
reqBody, err := json.Marshal(in)
227+
reqBody, err := {{$json}}.Marshal(in)
227228
if err != nil {
228229
return nil, ErrWebrpcRequestFailed.WithCausef("failed to marshal JSON body: %w", err)
229230
}
@@ -248,7 +249,7 @@ func doHTTPRequest(ctx context.Context, client HTTPClient, url string, in, out i
248249
}
249250

250251
var rpcErr WebRPCError
251-
if err := json.Unmarshal(respBody, &rpcErr); err != nil {
252+
if err := {{$json}}.Unmarshal(respBody, &rpcErr); err != nil {
252253
return nil, ErrWebrpcBadResponse.WithCausef("failed to unmarshal server error: %w", err)
253254
}
254255
if rpcErr.Cause != "" {
@@ -263,7 +264,7 @@ func doHTTPRequest(ctx context.Context, client HTTPClient, url string, in, out i
263264
return nil, ErrWebrpcBadResponse.WithCausef("failed to read response body: %w", err)
264265
}
265266

266-
err = json.Unmarshal(respBody, &out)
267+
err = {{$json}}.Unmarshal(respBody, &out)
267268
if err != nil {
268269
return nil, ErrWebrpcBadResponse.WithCausef("failed to unmarshal JSON response body: %w", err)
269270
}

imports.go.tmpl

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ import (
7070
{{- if eq $opts.json "stdlib" -}}
7171
{{- /* Already imported in the stdlib section. */ -}}
7272
{{- else if eq $opts.json "jsoniter" -}}
73-
{{- set $imports "github.com/json-iterator/go" "jsoniter" -}}
73+
{{- set $imports "github.com/json-iterator/go" "" -}}
7474
{{- else if eq $opts.json "sonic" -}}
7575
{{- set $imports "github.com/bytedance/sonic" "" -}}
7676
{{- else -}}
@@ -108,14 +108,14 @@ import (
108108
{{- if eq $opts.json "jsoniter" }}
109109

110110
// Opinionated config for -json=jsoniter, see https://github.com/json-iterator/go/blob/master/config.go.
111-
var json = jsoniter.Config{
111+
var jsonCfg = jsoniter.Config{
112112
ValidateJsonRawMessage: true,
113113
}.Froze()
114114

115115
{{- else if eq $opts.json "sonic" }}
116116

117117
// Opinionated config for -json=sonic, see https://github.com/bytedance/sonic/blob/main/api.go.
118-
var json = sonic.Config{
118+
var jsonCfg = sonic.Config{
119119
NoNullSliceOrMap: true, // Encode empty Array or Object as '[]' or '{}' instead of 'null'.
120120
CompactMarshaler: true,
121121
CopyString : true,

main.go.tmpl

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -157,12 +157,18 @@ func parseWebrpcGenVersions(header string) (*WebrpcGenVersions, error) {
157157
{{ template "types" dict "Services" .Services "Types" .Types "TypeMap" $typeMap "TypePrefix" $typePrefix "Opts" $opts }}
158158
{{ end -}}
159159

160+
{{- /* Allow using custom JSON configuration. */ -}}
161+
{{- $json := "json" -}}
162+
{{- if or (eq $opts.json "jsoniter") (eq $opts.json "sonic") -}}
163+
{{- $json = "jsonCfg" -}}
164+
{{- end -}}
165+
160166
{{- if $opts.server }}
161-
{{ template "server" dict "Services" .Services "TypeMap" $typeMap "TypePrefix" $typePrefix "Opts" $opts }}
167+
{{ template "server" dict "Services" .Services "TypeMap" $typeMap "TypePrefix" $typePrefix "Json" $json "Opts" $opts }}
162168
{{ end -}}
163169

164170
{{ if $opts.client }}
165-
{{ template "client" dict "Services" .Services "TypeMap" $typeMap "Opts" $opts "TypePrefix" $typePrefix }}
171+
{{ template "client" dict "Services" .Services "TypeMap" $typeMap "Json" $json "Opts" $opts "TypePrefix" $typePrefix }}
166172
{{ end -}}
167173

168174
{{ template "helpers" dict "Opts" $opts }}

server.go.tmpl

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
{{- $services := .Services -}}
33
{{- $typeMap := .TypeMap -}}
44
{{- $typePrefix := .TypePrefix -}}
5+
{{- $json := .Json -}}
56
{{- $opts := .Opts -}}
67

78
{{- if $services -}}
@@ -109,7 +110,7 @@ func (s *{{$serviceName}}) serve{{firstLetterToUpper $method.Name}}JSON(ctx cont
109110
Arg{{$i}} {{template "field" dict "Name" $input.Name "Type" $input.Type "Optional" $input.Optional "TypeMap" $typeMap "TypePrefix" $typePrefix "TypeMeta" $input.Meta "JsonTags" true}}
110111
{{- end}}
111112
}{}
112-
if err := json.Unmarshal(reqBody, &reqPayload); err != nil {
113+
if err := {{$json}}.Unmarshal(reqBody, &reqPayload); err != nil {
113114
s.sendErrorJSON(w, r, ErrWebrpcBadRequest.WithCausef("failed to unmarshal request data: %w", err))
114115
return
115116
}
@@ -138,9 +139,9 @@ func (s *{{$serviceName}}) serve{{firstLetterToUpper $method.Name}}JSON(ctx cont
138139

139140
{{- if $method.Outputs | len}}
140141
{{ if $opts.fixEmptyArrays -}}
141-
respBody, err := json.Marshal(initializeNilSlices(respPayload))
142+
respBody, err := {{$json}}.Marshal(initializeNilSlices(respPayload))
142143
{{ else -}}
143-
respBody, err := json.Marshal(respPayload)
144+
respBody, err := {{$json}}.Marshal(respPayload)
144145
{{ end -}}
145146
if err != nil {
146147
s.sendErrorJSON(w, r, ErrWebrpcBadResponse.WithCausef("failed to marshal json response: %w", err))
@@ -174,7 +175,7 @@ func (s *{{$serviceName}}) serve{{firstLetterToUpper $method.Name}}JSONStream(ct
174175
Arg{{$i}} {{template "field" dict "Name" $input.Name "Type" $input.Type "Optional" $input.Optional "TypeMap" $typeMap "TypePrefix" $typePrefix "TypeMeta" $input.Meta "JsonTags" true}}
175176
{{- end}}
176177
}{}
177-
if err := json.Unmarshal(reqBody, &reqPayload); err != nil {
178+
if err := {{$json}}.Unmarshal(reqBody, &reqPayload); err != nil {
178179
s.sendErrorJSON(w, r, ErrWebrpcBadRequest.WithCausef("failed to unmarshal request data: %w", err))
179180
return
180181
}
@@ -192,7 +193,7 @@ func (s *{{$serviceName}}) serve{{firstLetterToUpper $method.Name}}JSONStream(ct
192193
w.Header().Set("X-Content-Type-Options", "nosniff")
193194
w.WriteHeader(http.StatusOK)
194195

195-
streamWriter := &{{firstLetterToLower $method.Name}}StreamWriter{streamWriter{w: w, f: f, e: json.NewEncoder(w), sendError: s.sendErrorJSON}}
196+
streamWriter := &{{firstLetterToLower $method.Name}}StreamWriter{streamWriter{w: w, f: f, e: {{$json}}.NewEncoder(w), sendError: s.sendErrorJSON}}
196197
if err := streamWriter.ping(); err != nil {
197198
s.sendErrorJSON(w, r, ErrWebrpcStreamLost.WithCausef("failed to establish SSE stream: %w", err))
198199
return
@@ -226,15 +227,15 @@ func (s *{{$serviceName}}) sendErrorJSON(w http.ResponseWriter, r *http.Request,
226227
out := struct {
227228
WebRPCError WebRPCError `json:"webrpcError"`
228229
}{ WebRPCError: rpcErr }
229-
json.NewEncoder(w).Encode(out)
230+
{{$json}}.NewEncoder(w).Encode(out)
230231
return
231232
}
232233
{{- end }}
233234

234235
w.Header().Set("Content-Type", "application/json")
235236
w.WriteHeader(rpcErr.HTTPStatus)
236237

237-
respBody, _ := json.Marshal(rpcErr)
238+
respBody, _ := {{$json}}.Marshal(rpcErr)
238239
w.Write(respBody)
239240
}
240241
{{- end}}
@@ -248,7 +249,7 @@ func RespondWithError(w http.ResponseWriter, err error) {
248249
w.Header().Set("Content-Type", "application/json")
249250
w.WriteHeader(rpcErr.HTTPStatus)
250251

251-
respBody, _ := json.Marshal(rpcErr)
252+
respBody, _ := {{$json}}.Marshal(rpcErr)
252253
w.Write(respBody)
253254
}
254255

0 commit comments

Comments
 (0)