mirror of
https://github.com/foomo/contentserver.git
synced 2025-10-16 12:25:44 +00:00
63 lines
1.3 KiB
Go
63 lines
1.3 KiB
Go
package client
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"io/ioutil"
|
|
"net/http"
|
|
|
|
"github.com/foomo/contentserver/server"
|
|
)
|
|
|
|
type httpTransport struct {
|
|
client *http.Client
|
|
endpoint string
|
|
}
|
|
|
|
func newHTTPTransport(server string) transport {
|
|
return &httpTransport{
|
|
endpoint: server,
|
|
client: http.DefaultClient,
|
|
}
|
|
}
|
|
|
|
func (ht *httpTransport) shutdown() {
|
|
// nothing to do here
|
|
}
|
|
|
|
func (ht *httpTransport) call(handler server.Handler, request interface{}, response interface{}) error {
|
|
requestBytes, errMarshal := json.Marshal(request)
|
|
if errMarshal != nil {
|
|
return errMarshal
|
|
}
|
|
req, errNewRequest := http.NewRequest(
|
|
http.MethodPost,
|
|
ht.endpoint+"/"+string(handler),
|
|
bytes.NewBuffer(requestBytes),
|
|
)
|
|
if errNewRequest != nil {
|
|
return errNewRequest
|
|
}
|
|
httpResponse, errDo := ht.client.Do(req)
|
|
if errDo != nil {
|
|
return errDo
|
|
}
|
|
if httpResponse.StatusCode != http.StatusOK {
|
|
return errors.New("non 200 reply")
|
|
}
|
|
if httpResponse.Body == nil {
|
|
return errors.New("empty response body")
|
|
}
|
|
responseBytes, errRead := ioutil.ReadAll(httpResponse.Body)
|
|
httpResponse.Body.Close()
|
|
if errRead != nil {
|
|
return errRead
|
|
}
|
|
errUnmarshal := json.Unmarshal(responseBytes, &serverResponse{Reply: response})
|
|
if errUnmarshal != nil {
|
|
return errUnmarshal
|
|
}
|
|
return errUnmarshal
|
|
}
|