github.com/nyan233/littlerpc@v0.4.6-0.20230316182519-0c8d5c48abaf/cmd/pxtor/method.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "strings" 6 ) 7 8 type Argument struct { 9 Name string 10 Type string 11 } 12 13 type Statement struct { 14 ReceiveName string 15 CallFunc string 16 InputList []string 17 OutputList []string 18 } 19 20 type Method struct { 21 Receive Argument 22 ServiceName string 23 Name string 24 InputList []Argument 25 OutputList []Argument 26 Statement Statement 27 } 28 29 func (m *Method) FormatToSync() string { 30 var sb strings.Builder 31 _, _ = fmt.Fprintf(&sb, "func(%s %s) %s", m.Receive.Name, m.Receive.Type, m.Name) 32 sb2 := strings.Builder{} 33 inputNames := strings.Builder{} 34 for _, arg := range m.InputList { 35 _, _ = fmt.Fprintf(&sb2, "%s %s,", arg.Name, arg.Type) 36 _, _ = fmt.Fprintf(&inputNames, "%s,", arg.Name) 37 } 38 _, _ = fmt.Fprintf(&sb, "(%sopts ...client.CallOption)", sb2.String()) 39 sb2.Reset() 40 var nop string 41 if len(m.OutputList) > 1 { 42 nop = "," 43 } 44 for _, arg := range m.OutputList { 45 if arg.Name == "" { 46 _, _ = fmt.Fprintf(&sb2, "%s%s", arg.Type, nop) 47 } else { 48 _, _ = fmt.Fprintf(&sb2, "%s %s%s", arg.Name, arg.Type, nop) 49 } 50 } 51 if len(m.OutputList) > 1 { 52 _, _ = fmt.Fprintf(&sb, "(%s)", sb2.String()) 53 } else { 54 _, _ = fmt.Fprintf(&sb, "%s", sb2.String()) 55 } 56 var outNames strings.Builder 57 var assertSet strings.Builder 58 for i := 0; i < len(m.OutputList)-1; i++ { 59 _, _ = fmt.Fprintf(&assertSet, "r%d,_ := reps[%d].(%s);", i, i, m.OutputList[i].Type) 60 _, _ = fmt.Fprintf(&outNames, "r%d,", i) 61 } 62 if len(m.OutputList) == 1 { 63 _, _ = fmt.Fprintf(&sb, "{_,err := %s.Call(\"%s\",opts,%s);%sreturn %serr}", m.Receive.Name, m.ServiceName, 64 inputNames.String(), assertSet.String(), outNames.String()) 65 } else if len(m.OutputList) > 1 { 66 _, _ = fmt.Fprintf(&sb, "{reps,err := %s.Call(\"%s\",opts,%s);%sreturn %serr}", m.Receive.Name, m.ServiceName, 67 inputNames.String(), assertSet.String(), outNames.String()) 68 } 69 return sb.String() 70 } 71 72 func (m *Method) FormatToASync() string { 73 return "" 74 } 75 76 func (m *Method) FormatToRequests() string { 77 return "" 78 }