apigen/test/demo/cli/cli.go

91 lines
1.5 KiB
Go
Raw Normal View History

2021-10-03 14:39:42 +00:00
package api
import "time"
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"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
}
type SomeReq struct {
Fielda string
Fieldb time.Time
}
type SomeReq2 struct {
Fielda string
Fieldb time.Time
}
type SomeRes struct {
Msg string
}
func Dosome(req *SomeReq) (res *SomeRes, err error) {
var dec *json.Decoder
dec, err = invoke("POST", "/some", req)
if err != nil {
return
}
var ret *SomeRes = &SomeRes{}
err = dec.Decode(ret)
return ret, err
}
func Dosome2(req *SomeReq2) (res *SomeRes, err error) {
var dec *json.Decoder
dec, err = invoke("POST", "/some2", req)
if err != nil {
return
}
var ret *SomeRes = &SomeRes{}
err = dec.Decode(ret)
return ret, err
}