-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
44 lines (39 loc) · 1.33 KB
/
response.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package gin_grpc
import (
"fmt"
"reflect"
)
type Response struct {
resp any
}
// Set the rpc response.
func (r *Response) Set(resp any) {
if reflect.TypeOf(r.resp) != reflect.TypeOf(resp) {
panic(fmt.Errorf("internal error: response type mismatch: %s != %s", reflect.TypeOf(r.resp).Name(), reflect.TypeOf(resp).Name()))
}
r.resp = resp
}
// SetField set the rpc response field with the given value.
// if the field not found, it will panic.
// if the type of the value is not the same as the field, it will try to convert it, if it fails, it will panic.
func (r *Response) SetField(field string, value any) {
fieldValue := reflect.ValueOf(r.resp).Elem().FieldByName(field)
if !fieldValue.IsValid() {
panic(fmt.Errorf("internal error: response field not found: %s", field))
}
valueValue := reflect.ValueOf(value)
if fieldValue.Type().Kind() != valueValue.Type().Kind() {
if valueValue.CanConvert(fieldValue.Type()) {
fieldValue.Set(valueValue.Convert(fieldValue.Type()))
return
}
panic(fmt.Errorf("internal error: response field type mismatch: %s != %s", fieldValue.Type().Name(), reflect.TypeOf(value).Name()))
}
fieldValue.Set(reflect.ValueOf(value))
}
// SetFields set the rpc response fields with the given values
func (r *Response) SetFields(fields H) {
for field, value := range fields {
r.SetField(field, value)
}
}