apigen/lib/processGoClientOutput.go

157 lines
2.7 KiB
Go

package lib
import (
"bytes"
"fmt"
"log"
"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)
for k, v := range api.UsedImportsFunctions {
log.Printf("Adding import from funcions: %s => %s", k, v)
WNL(`import "%s"`, k)
}
for k, v := range api.UsedImportsTypes {
log.Printf("Adding import from types: %s => %s", k, v)
WNL(`import "%s"`, k)
}
WNL(`import (
"bytes"
"errors"
"io/ioutil"
"encoding/json"
"net/http"
)
var Basepath string = ""
var Host string = ""
var ExtraHeaders map[string]string = make(map[string]string)
var cli *http.Client
func SetCli(nc *http.Client) {
cli = nc
}
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)
}
res, err := cli.Do(req)
if err != nil {
return nil, err
}
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 {
WNL("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)
}