apigen/test/gocli/apicli.go

72 lines
1.3 KiB
Go

package gocli
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
}
func Some() (*struct{}, error) {
dec, err := invoke("a", "/c/d", struct{}{})
ret := &struct{}{}
dec.Decode(ret)
return ret, err
}
type ARequestStruct struct {
A string `json:"a"`
B int64 `json:"b"`
C time.Time `json:"c"`
D string `json:"d"`
}
type AResponseStruct struct {
A string `json:"a"`
B int64 `json:"b"`
C time.Time `json:"c"`
D string `json:"d"`
}
func SomeAPI(req *ARequestStruct) (res *AResponseStruct, err error) {
dec, err := invoke("POST", "/someapi", req)
ret := &AResponseStruct{}
err = dec.Decode(ret)
if err != nil {
return nil, err
}
return ret, err
}