apigen/lib/processGoClientOutput.go

142 lines
2.4 KiB
Go

package lib
import (
"bytes"
"fmt"
"os"
)
import (
_ "embed"
)
func processGoClientOutput(f string) error {
buf := &bytes.Buffer{}
W := func(s string, p ...interface{}) {
buf.WriteString(fmt.Sprintf(s, p...))
}
WNL := func(s string, p ...interface{}) {
buf.WriteString(fmt.Sprintf(s+"\n", p...))
}
ResDecType := func(v *APIParamType) string {
ret := ""
if v.IsArray {
ret = ret + "[]"
}
if v.Ispointer {
ret = ret + "*"
}
ret += " " + v.Typename
return ret
}
ResImplType := func(v *APIParamType) string {
ret := ""
if v.IsArray {
ret = ret + "[]"
}
if v.Ispointer {
ret = ret + "*"
}
ret += v.Typename
ret += " = "
if !v.IsArray || v.Ispointer {
ret = ret + "&"
}
ret += v.Typename + "{}"
return ret
}
WNL("package %s", api.Namespace)
WNL(`import (
"bytes"
"errors"
"io/ioutil"
"encoding/json"
"net/http"
"time"
)
var Basepath string = ""
var Host string = ""
var ExtraHeaders map[string]string = make(map[string]string)
func invoke(m string, path string, bodyo interface{}) (*json.Decoder, error) {
b := &bytes.Buffer{}
err := json.NewEncoder(b).Encode(bodyo)
if err != nil {
return nil, err
}
body := bytes.NewReader(b.Bytes())
req, err := http.NewRequest(m, Host+Basepath+path, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-type", "application/json")
for k, v := range ExtraHeaders {
req.Header.Set(k, v)
}
cli := http.Client{}
res, err := cli.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode >= 400 {
bs, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil,err
}
return nil, errors.New(string(bs))
}
ret := json.NewDecoder(res.Body)
return ret, nil
}
`)
for k, v := range api.Types {
WNL(`type %s struct {`, k)
for fn, f := range v.Fields {
W(` %s `, fn)
if f.Array {
W("[]")
}
if f.Map {
W("map[%s]%s", f.Mapkey, f.Mapval)
} else {
WNL(f.Type)
}
}
WNL(`}`)
}
for k, v := range api.Methods {
WNL(`func %s(req %s) (res %s, err error){`, k, ResDecType(v.ReqType), ResDecType(v.ResType))
WNL(` var dec *json.Decoder
dec, err = invoke("%s", "%s", req)
if err!=nil{
return
}
var ret %s`, v.Verb, v.Path, ResImplType(v.ResType))
W(` err = dec.Decode(`)
if v.ResType.IsArray || !v.ResType.Ispointer {
W("&")
}
WNL(`ret)
return ret, err
}`)
}
return os.WriteFile(f, buf.Bytes(), 0600)
}