2 回答

TA貢獻1877條經驗 獲得超6個贊
因為您只處理函數,所以可以使用 reflect 包在運行時生成函數。
使用對象類型 (Volume, Vpc) 可以導出所有后續信息,以提供一個完全通用的實現,該實現非??菰?,甚至更復雜、更慢。
package main
import (
? ? "errors"
? ? "fmt"
? ? "reflect"
)
func main() {
? ? fmt.Printf("%T\n", getter(Volume{}))
? ? fmt.Printf("%T\n", getter(Vpc{}))
}
type DescribeVolumesInput struct{}
type DescribeVpcs struct{}
type Volume struct{}
type Vpc struct{}
type Session struct{}
type Client struct{}
func New(s *Session) Client { return Client{} }
var typeRegistry = make(map[string]reflect.Type)
func init() {
? ? some := []interface{}{DescribeVolumesInput{}, DescribeVpcs{}}
? ? for _, v := range some {
? ? ? ? typeRegistry[fmt.Sprintf("%T", v)] = reflect.TypeOf(v)
? ? }
}
var errV = errors.New("")
var errType = reflect.ValueOf(&errV).Elem().Type()
var zeroErr = reflect.Zero(reflect.TypeOf((*error)(nil)).Elem())
var nilErr = []reflect.Value{zeroErr}
func getter(of interface{}) interface{} {
? ? outType := reflect.SliceOf(reflect.PtrTo(reflect.TypeOf(of)))
? ? fnType := reflect.FuncOf([]reflect.Type{reflect.TypeOf(new(Session))}, []reflect.Type{outType, errType}, false)
? ? fnBody := func(input []reflect.Value) []reflect.Value {
? ? ? ? client := reflect.ValueOf(New).Call(input)[0]
? ? ? ? t := reflect.MakeSlice(outType, 0, 0)
? ? ? ? name := fmt.Sprintf("Describe%TsInput", of)
? ? ? ? descInput := reflect.New(typeRegistry[name]).Elem()
? ? ? ? mName := fmt.Sprintf("Describe%Ts", of)
? ? ? ? meth := client.MethodByName(mName)
? ? ? ? if !meth.IsValid() {
? ? ? ? ? ? return []reflect.Value{
? ? ? ? ? ? ? ? t,
? ? ? ? ? ? ? ? reflect.ValueOf(fmt.Errorf("no such method %q", mName)),
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? for {
? ? ? ? ? ? out := meth.Call([]reflect.Value{descInput.Addr()})
? ? ? ? ? ? if len(out) > 0 {
? ? ? ? ? ? ? ? errOut := out[len(out)-1]
? ? ? ? ? ? ? ? if errOut.Type().Implements(errType) && errOut.IsNil() == false {
? ? ? ? ? ? ? ? ? ? return []reflect.Value{t, errOut}
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? result := out[1]
? ? ? ? ? ? fName := fmt.Sprintf("%Ts", of)
? ? ? ? ? ? if x := result.FieldByName(fName); x.IsValid() {
? ? ? ? ? ? ? ? t = reflect.AppendSlice(t, x)
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? return []reflect.Value{
? ? ? ? ? ? ? ? ? ? t,
? ? ? ? ? ? ? ? ? ? reflect.ValueOf(fmt.Errorf("field not found %q", fName)),
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? if x := result.FieldByName("NextToken"); x.IsValid() {
? ? ? ? ? ? ? ? descInput.FieldByName("NextToken").Set(x)
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? break
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return []reflect.Value{t, zeroErr}
? ? }
? ? fn := reflect.MakeFunc(fnType, fnBody)
? ? return fn.Interface()
}

TA貢獻1772條經驗 獲得超5個贊
代理第 3 方 API,用 go 實現非常簡單,下面是它是如何用 endly e2e test runner?AWS 代理實現的
我會說 AWS API 是代理的完美候選者,只要反射性能價格不是問題。
像kubernetes這樣的其他一些第三方 API?更具挑戰性,但仍然很容易用 go 代理,這是反射和代碼生成的結合。
- 2 回答
- 0 關注
- 159 瀏覽
添加回答
舉報