apigen/test/gocli/apicli.go

117 lines
2.1 KiB
Go

package gocli
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"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
}
if res.StatusCode >= 400 {
bs, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err)
}
return nil, errors.New(string(bs))
}
ret := json.NewDecoder(res.Body)
return ret, nil
}
type ARequestStruct struct {
C time.Time `json:"c"`
D string `json:"d"`
A string `json:"a"`
B int64 `json:"b"`
}
type AResponseStruct struct {
A string `json:"a"`
B int64 `json:"b"`
C time.Time `json:"c"`
D string `json:"d"`
}
type AStr struct {
A string `json:"a"`
B []string `json:"b"`
}
type AStr2 struct {
X string `json:"x"`
Y []string `json:"y"`
Z []AStr `json:"z"`
W map[string]AStr `json:"w"`
}
func SomeAPI3(req *AStr) (res []*AStr, err error) {
var dec *json.Decoder
dec, err = invoke("POST", "/someapi3", req)
if err != nil {
return
}
ret := []*AStr{}
err = dec.Decode(&ret)
if err != nil {
return nil, err
}
return ret, err
}
func SomeAPI(req *AStr) (res []*AStr, err error) {
var dec *json.Decoder
dec, err = invoke("PUT", "/someapi", req)
if err != nil {
return
}
ret := []*AStr{}
err = dec.Decode(&ret)
if err != nil {
return nil, err
}
return ret, err
}
func SomeAPI2(req *AStr) (res []*AStr, err error) {
var dec *json.Decoder
dec, err = invoke("POST", "/someapi", req)
if err != nil {
return
}
ret := []*AStr{}
err = dec.Decode(&ret)
if err != nil {
return nil, err
}
return ret, err
}