apigen/test/gocli/apicli.go

53 lines
977 B
Go
Raw Normal View History

2020-11-06 23:16:52 +00:00
package gocli
import (
"bytes"
"encoding/json"
"net/http"
)
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
}
2020-12-12 12:21:12 +00:00
type AStr struct {
A string `json:"a"`
2020-11-06 23:16:52 +00:00
}
2020-12-12 12:21:12 +00:00
func SomeAPI2(req *AStr) (res []*AStr, err error) {
2020-11-06 23:16:52 +00:00
dec, err := invoke("POST", "/someapi", req)
2020-12-12 12:21:12 +00:00
ret := []*AStr{}
2020-11-06 23:16:52 +00:00
err = dec.Decode(ret)
if err != nil {
return nil, err
}
return ret, err
}