1
0
mirror of https://github.com/go-micro/go-micro.git synced 2024-12-24 10:07:04 +02:00
go-micro/server/extractor.go

130 lines
2.1 KiB
Go
Raw Normal View History

package server
import (
"fmt"
"reflect"
2016-07-30 20:01:42 +02:00
"strings"
2015-11-20 18:17:33 +02:00
"github.com/micro/go-micro/registry"
)
func extractValue(v reflect.Type, d int) *registry.Value {
if d == 3 {
return nil
}
if v == nil {
return nil
}
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
2019-03-19 02:21:25 +02:00
if len(v.Name()) == 0 {
return nil
}
arg := &registry.Value{
Name: v.Name(),
Type: v.Name(),
}
switch v.Kind() {
case reflect.Struct:
for i := 0; i < v.NumField(); i++ {
2016-07-30 20:01:42 +02:00
f := v.Field(i)
val := extractValue(f.Type, d+1)
if val == nil {
continue
}
2016-07-30 20:01:42 +02:00
// if we can find a json tag use it
if tags := f.Tag.Get("json"); len(tags) > 0 {
parts := strings.Split(tags, ",")
2019-03-19 02:21:25 +02:00
if parts[0] == "-" || parts[0] == "omitempty" {
continue
}
2016-07-30 20:01:42 +02:00
val.Name = parts[0]
}
// if there's no name default it
if len(val.Name) == 0 {
val.Name = v.Field(i).Name
}
2019-03-19 02:21:25 +02:00
// still no name then continue
if len(val.Name) == 0 {
continue
}
arg.Values = append(arg.Values, val)
}
case reflect.Slice:
p := v.Elem()
if p.Kind() == reflect.Ptr {
p = p.Elem()
}
arg.Type = "[]" + p.Name()
val := extractValue(v.Elem(), d+1)
if val != nil {
arg.Values = append(arg.Values, val)
}
}
return arg
}
func extractEndpoint(method reflect.Method) *registry.Endpoint {
if method.PkgPath != "" {
return nil
}
var rspType, reqType reflect.Type
var stream bool
mt := method.Type
switch mt.NumIn() {
case 3:
reqType = mt.In(1)
rspType = mt.In(2)
case 4:
reqType = mt.In(2)
rspType = mt.In(3)
default:
return nil
}
// are we dealing with a stream?
switch rspType.Kind() {
case reflect.Func, reflect.Interface:
stream = true
}
request := extractValue(reqType, 0)
response := extractValue(rspType, 0)
return &registry.Endpoint{
Name: method.Name,
Request: request,
Response: response,
Metadata: map[string]string{
"stream": fmt.Sprintf("%v", stream),
},
}
}
func extractSubValue(typ reflect.Type) *registry.Value {
var reqType reflect.Type
switch typ.NumIn() {
case 1:
reqType = typ.In(0)
case 2:
reqType = typ.In(1)
2015-12-03 02:49:58 +02:00
case 3:
reqType = typ.In(2)
default:
return nil
}
return extractValue(reqType, 0)
}