apigen/test/gocli/cli.go

85 lines
1.4 KiB
Go
Raw Permalink Normal View History

2021-04-02 14:40:28 +00:00
package goapi
2021-10-03 14:39:42 +00:00
import "time"
import "crypto"
2021-04-02 14:40:28 +00:00
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
)
var Basepath string = ""
var Host string = ""
var ExtraHeaders map[string]string = make(map[string]string)
2021-10-03 14:39:42 +00:00
var Ver string = ""
var cli http.Client
func SetCli(nc http.Client) {
cli = nc
}
2021-04-02 14:40:28 +00:00
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
}
2021-10-03 14:39:42 +00:00
2021-04-02 14:40:28 +00:00
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
}
2021-10-03 14:39:42 +00:00
defer res.Body.Close()
2021-04-02 14:40:28 +00:00
if res.StatusCode >= 400 {
bs, err := ioutil.ReadAll(res.Body)
if err != nil {
2021-10-03 14:39:42 +00:00
return nil, err
2021-04-02 14:40:28 +00:00
}
return nil, errors.New(string(bs))
}
ret := json.NewDecoder(res.Body)
return ret, nil
}
type AStr struct {
2021-10-03 14:39:42 +00:00
HouseNumber int64
2021-04-02 14:40:28 +00:00
SomeWeirdTest string
2021-10-03 14:39:42 +00:00
Recursive map[string]AStr
When time.Time
Some crypto.Decrypter
Country string
City string
IsCondo bool
Arrofpstr []string
2021-04-02 14:40:28 +00:00
}
2021-10-03 14:39:42 +00:00
func SomeAPI(req *AStr) (res *AStr, err error) {
2021-04-02 14:40:28 +00:00
var dec *json.Decoder
dec, err = invoke("POST", "/someapi", req)
if err != nil {
return
}
2021-10-03 14:39:42 +00:00
var ret *AStr = &AStr{}
2021-04-02 14:40:28 +00:00
err = dec.Decode(ret)
return ret, err
}