apigen/processGoClientOutput.go

99 lines
1.9 KiB
Go
Raw Normal View History

2020-11-06 23:16:52 +00:00
package main
import (
"bytes"
"fmt"
2020-11-22 12:05:45 +00:00
dc "go.digitalcircle.com.br/golib/base"
2020-11-06 23:16:52 +00:00
"io/ioutil"
"strings"
)
func processGoClientOutput(api *API) {
b := bytes.Buffer{}
f := config.Goclifname
fparts := strings.Split(f, "/")
pkg := fparts[len(fparts)-2]
b.WriteString(fmt.Sprintf(`package %s
import (
"bytes"
"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
}
ret := json.NewDecoder(res.Body)
return ret, nil
}
`, pkg))
for k, v := range api.Types {
b.WriteString(fmt.Sprintf("type %s struct {\n", k))
for kf, f := range v.Fields {
ftype := f.Type
if f.Array {
ftype = "[]" + ftype
} else if f.Map {
fm := f.Mapkey
fv := f.Mapval
ftype = "map[" + fm + "]" + fv
}
b.WriteString(fmt.Sprintf("\t%s %s `json:\"%s\"` \n", strings.ToUpper(kf[:1])+strings.ToLower(kf[1:]), ftype, strings.ToLower(kf)))
}
b.WriteString(fmt.Sprintf("}\n\n"))
}
for k, m := range api.Methods {
b.WriteString(fmt.Sprintf("func %s(req *%s) (res *%s, err error){\n", k, m.ReqType.Typename, m.ResType.Typename))
b.WriteString(fmt.Sprintf(` dec, err := invoke("%s", "%s", req)
ret := &%s{}
err = dec.Decode(ret)
if err != nil{
return nil,err
}
return ret, err
}`, m.Verb, m.Path, m.ResType.Typename))
//}
}
err := ioutil.WriteFile(f, b.Bytes(), 0600)
dc.Err(err)
}