85 lines
1.4 KiB
Go
85 lines
1.4 KiB
Go
package goapi
|
|
|
|
import "time"
|
|
import "crypto"
|
|
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 Ver 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
|
|
}
|
|
|
|
defer res.Body.Close()
|
|
|
|
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 AStr struct {
|
|
HouseNumber int64
|
|
SomeWeirdTest string
|
|
Recursive map[string]AStr
|
|
When time.Time
|
|
Some crypto.Decrypter
|
|
Country string
|
|
City string
|
|
IsCondo bool
|
|
Arrofpstr []string
|
|
}
|
|
|
|
func SomeAPI(req *AStr) (res *AStr, err error) {
|
|
var dec *json.Decoder
|
|
dec, err = invoke("POST", "/someapi", req)
|
|
if err != nil {
|
|
return
|
|
}
|
|
var ret *AStr = &AStr{}
|
|
err = dec.Decode(ret)
|
|
return ret, err
|
|
}
|