Example #1
0
func (c *rpcPlusCodec) WriteRequest(req *rpc.Request, body interface{}) error {
	c.wbuf.Reset()
	buf := &buffer{c.wbuf}

	var cc rpc.ClientCodec
	switch c.req.Header["Content-Type"] {
	case "application/octet-stream":
		cc = pb.NewClientCodec(buf)
	case "application/json":
		cc = js.NewClientCodec(buf)
	default:
		return fmt.Errorf("unsupported request type: %s", c.req.Header["Content-Type"])
	}

	if err := cc.WriteRequest(req, body); err != nil {
		return err
	}

	c.req.Body = c.wbuf.Bytes()
	return c.client.Send(c.req)
}
Example #2
0
func (r *RpcClient) call(address, path string, request Request, response interface{}) error {
	pReq := &rpc.Request{
		ServiceMethod: request.Method(),
	}

	reqB := bytes.NewBuffer(nil)
	defer reqB.Reset()
	buf := &buffer{
		reqB,
	}

	var cc rpc.ClientCodec
	switch request.ContentType() {
	case "application/octet-stream":
		cc = pb.NewClientCodec(buf)
	case "application/json":
		cc = js.NewClientCodec(buf)
	default:
		return errors.InternalServerError("go.micro.client", fmt.Sprintf("Unsupported request type: %s", request.ContentType()))
	}

	err := cc.WriteRequest(pReq, request.Request())
	if err != nil {
		return errors.InternalServerError("go.micro.client", fmt.Sprintf("Error writing request: %v", err))
	}

	client := &http.Client{}
	client.Transport = &headerRoundTripper{http.DefaultTransport}

	request.Headers().Set("Content-Type", request.ContentType())

	hreq := &http.Request{
		Method: "POST",
		URL: &url.URL{
			Scheme: "http",
			Host:   address,
			Path:   path,
		},
		Header:        request.Headers().(http.Header),
		Body:          buf,
		ContentLength: int64(reqB.Len()),
		Host:          address,
	}

	rsp, err := client.Do(hreq)
	if err != nil {
		return errors.InternalServerError("go.micro.client", fmt.Sprintf("Error sending request: %v", err))
	}
	defer rsp.Body.Close()

	b, err := ioutil.ReadAll(rsp.Body)
	if err != nil {
		return errors.InternalServerError("go.micro.client", fmt.Sprintf("Error reading response: %v", err))
	}

	rspB := bytes.NewBuffer(b)
	defer rspB.Reset()
	rBuf := &buffer{
		rspB,
	}

	switch rsp.Header.Get("Content-Type") {
	case "application/octet-stream":
		cc = pb.NewClientCodec(rBuf)
	case "application/json":
		cc = js.NewClientCodec(rBuf)
	default:
		return errors.InternalServerError("go.micro.client", string(b))
	}

	pRsp := &rpc.Response{}
	err = cc.ReadResponseHeader(pRsp)
	if err != nil {
		return errors.InternalServerError("go.micro.client", fmt.Sprintf("Error reading response headers: %v", err))
	}

	if len(pRsp.Error) > 0 {
		return errors.Parse(pRsp.Error)
	}

	err = cc.ReadResponseBody(response)
	if err != nil {
		return errors.InternalServerError("go.micro.client", fmt.Sprintf("Error reading response body: %v", err))
	}

	return nil
}