2020-10-09 16:20:10 +03:00
|
|
|
package registry
|
2020-10-09 16:15:36 +03:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"reflect"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2020-10-09 16:20:10 +03:00
|
|
|
func ExtractValue(v reflect.Type, d int) *Value {
|
2020-10-09 16:15:36 +03:00
|
|
|
if d == 3 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if v == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if v.Kind() == reflect.Ptr {
|
|
|
|
v = v.Elem()
|
|
|
|
}
|
|
|
|
|
2020-10-09 16:20:10 +03:00
|
|
|
arg := &Value{
|
2020-10-09 16:15:36 +03:00
|
|
|
Name: v.Name(),
|
|
|
|
Type: v.Name(),
|
|
|
|
}
|
|
|
|
|
|
|
|
switch v.Kind() {
|
|
|
|
case reflect.Struct:
|
|
|
|
for i := 0; i < v.NumField(); i++ {
|
|
|
|
f := v.Field(i)
|
2020-10-09 16:20:10 +03:00
|
|
|
val := ExtractValue(f.Type, d+1)
|
2020-10-09 16:15:36 +03:00
|
|
|
if val == nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// if we can find a json tag use it
|
|
|
|
if tags := f.Tag.Get("json"); len(tags) > 0 {
|
|
|
|
parts := strings.Split(tags, ",")
|
|
|
|
if parts[0] == "-" || parts[0] == "omitempty" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
val.Name = parts[0]
|
|
|
|
}
|
|
|
|
|
|
|
|
// if there's no name default it
|
|
|
|
if len(val.Name) == 0 {
|
|
|
|
val.Name = v.Field(i).Name
|
|
|
|
}
|
|
|
|
|
|
|
|
arg.Values = append(arg.Values, val)
|
|
|
|
}
|
|
|
|
case reflect.Slice:
|
|
|
|
p := v.Elem()
|
|
|
|
if p.Kind() == reflect.Ptr {
|
|
|
|
p = p.Elem()
|
|
|
|
}
|
|
|
|
arg.Type = "[]" + p.Name()
|
|
|
|
}
|
|
|
|
|
|
|
|
return arg
|
|
|
|
}
|
|
|
|
|
2020-10-09 16:20:10 +03:00
|
|
|
func ExtractEndpoint(method reflect.Method) *Endpoint {
|
2020-10-09 16:15:36 +03:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2020-10-09 16:20:10 +03:00
|
|
|
request := ExtractValue(reqType, 0)
|
|
|
|
response := ExtractValue(rspType, 0)
|
2020-10-09 16:15:36 +03:00
|
|
|
|
2020-10-09 16:20:10 +03:00
|
|
|
ep := &Endpoint{
|
2020-10-09 16:15:36 +03:00
|
|
|
Name: method.Name,
|
|
|
|
Request: request,
|
|
|
|
Response: response,
|
|
|
|
Metadata: make(map[string]string),
|
|
|
|
}
|
|
|
|
|
|
|
|
if stream {
|
|
|
|
ep.Metadata = map[string]string{
|
|
|
|
"stream": fmt.Sprintf("%v", stream),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return ep
|
|
|
|
}
|