Compare commits
7 Commits
v3.9.17
...
4abfdccfe2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4abfdccfe2 | ||
| f5ea4d10d0 | |||
| f1cd388a6c | |||
|
|
fa00663740 | ||
|
|
523b3ca80e | ||
| 905398dcb6 | |||
| a6dd9c0455 |
@@ -1,5 +1,5 @@
|
|||||||
# HTTP Client
|
# HTTP Client
|
||||||

|

|
||||||
|
|
||||||
This plugin is an HTTP client for [Micro](https://pkg.go.dev/go.unistack.org/micro/v3).
|
This plugin is an HTTP client for [Micro](https://pkg.go.dev/go.unistack.org/micro/v3).
|
||||||
It implements the [micro.Client](https://pkg.go.dev/go.unistack.org/micro/v3/client#Client) interface.
|
It implements the [micro.Client](https://pkg.go.dev/go.unistack.org/micro/v3/client#Client) interface.
|
||||||
|
|||||||
131
client.go
131
client.go
@@ -3,25 +3,34 @@ package http
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"go.unistack.org/micro-client-http/v3/status"
|
||||||
|
"go.unistack.org/micro/v3/broker"
|
||||||
"go.unistack.org/micro/v3/client"
|
"go.unistack.org/micro/v3/client"
|
||||||
|
"go.unistack.org/micro/v3/codec"
|
||||||
"go.unistack.org/micro/v3/errors"
|
"go.unistack.org/micro/v3/errors"
|
||||||
|
"go.unistack.org/micro/v3/metadata"
|
||||||
"go.unistack.org/micro/v3/options"
|
"go.unistack.org/micro/v3/options"
|
||||||
"go.unistack.org/micro/v3/semconv"
|
"go.unistack.org/micro/v3/semconv"
|
||||||
"go.unistack.org/micro/v3/tracer"
|
"go.unistack.org/micro/v3/tracer"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var _ client.Client = (*Client)(nil)
|
||||||
|
|
||||||
var DefaultContentType = "application/json"
|
var DefaultContentType = "application/json"
|
||||||
|
|
||||||
type Client struct {
|
type Client struct {
|
||||||
funcCall client.FuncCall
|
funcPublish client.FuncPublish
|
||||||
funcStream client.FuncStream
|
funcBatchPublish client.FuncBatchPublish
|
||||||
httpClient *http.Client
|
funcCall client.FuncCall
|
||||||
opts client.Options
|
funcStream client.FuncStream
|
||||||
mu sync.RWMutex
|
httpClient *http.Client
|
||||||
|
opts client.Options
|
||||||
|
mu sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewClient(opts ...client.Option) *Client {
|
func NewClient(opts ...client.Option) *Client {
|
||||||
@@ -91,25 +100,45 @@ func (c *Client) NewRequest(service, method string, req any, opts ...client.Requ
|
|||||||
func (c *Client) Call(ctx context.Context, req client.Request, rsp any, opts ...client.CallOption) error {
|
func (c *Client) Call(ctx context.Context, req client.Request, rsp any, opts ...client.CallOption) error {
|
||||||
ts := time.Now()
|
ts := time.Now()
|
||||||
c.opts.Meter.Counter(semconv.ClientRequestInflight, "endpoint", req.Endpoint()).Inc()
|
c.opts.Meter.Counter(semconv.ClientRequestInflight, "endpoint", req.Endpoint()).Inc()
|
||||||
|
|
||||||
var sp tracer.Span
|
var sp tracer.Span
|
||||||
ctx, sp = c.opts.Tracer.Start(ctx, req.Endpoint()+" rpc-client",
|
ctx, sp = c.opts.Tracer.Start(ctx, req.Endpoint()+" rpc-client",
|
||||||
tracer.WithSpanKind(tracer.SpanKindClient),
|
tracer.WithSpanKind(tracer.SpanKindClient),
|
||||||
tracer.WithSpanLabels("endpoint", req.Endpoint()),
|
tracer.WithSpanLabels("endpoint", req.Endpoint()),
|
||||||
)
|
)
|
||||||
|
defer sp.Finish()
|
||||||
|
|
||||||
err := c.funcCall(ctx, req, rsp, opts...)
|
err := c.funcCall(ctx, req, rsp, opts...)
|
||||||
|
|
||||||
c.opts.Meter.Counter(semconv.ClientRequestInflight, "endpoint", req.Endpoint()).Dec()
|
c.opts.Meter.Counter(semconv.ClientRequestInflight, "endpoint", req.Endpoint()).Dec()
|
||||||
te := time.Since(ts)
|
te := time.Since(ts)
|
||||||
c.opts.Meter.Summary(semconv.ClientRequestLatencyMicroseconds, "endpoint", req.Endpoint()).Update(te.Seconds())
|
c.opts.Meter.Summary(semconv.ClientRequestLatencyMicroseconds, "endpoint", req.Endpoint()).Update(te.Seconds())
|
||||||
c.opts.Meter.Histogram(semconv.ClientRequestDurationSeconds, "endpoint", req.Endpoint()).Update(te.Seconds())
|
c.opts.Meter.Histogram(semconv.ClientRequestDurationSeconds, "endpoint", req.Endpoint()).Update(te.Seconds())
|
||||||
|
|
||||||
if me := errors.FromError(err); me == nil {
|
var (
|
||||||
sp.Finish()
|
statusCode int
|
||||||
c.opts.Meter.Counter(semconv.ClientRequestTotal, "endpoint", req.Endpoint(), "status", "success", "code", strconv.Itoa(int(200))).Inc()
|
statusLabel string
|
||||||
} else {
|
)
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
statusLabel = "success"
|
||||||
|
} else if st, ok := status.FromError(err); ok {
|
||||||
|
statusCode = st.Code()
|
||||||
|
statusLabel = "failure"
|
||||||
|
sp.SetStatus(tracer.SpanStatusError, err.Error())
|
||||||
|
} else if me := errors.FromError(err); me != nil {
|
||||||
|
statusCode = int(me.Code)
|
||||||
|
statusLabel = "failure"
|
||||||
|
sp.SetStatus(tracer.SpanStatusError, err.Error())
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
statusLabel = "failure"
|
||||||
sp.SetStatus(tracer.SpanStatusError, err.Error())
|
sp.SetStatus(tracer.SpanStatusError, err.Error())
|
||||||
c.opts.Meter.Counter(semconv.ClientRequestTotal, "endpoint", req.Endpoint(), "status", "failure", "code", strconv.Itoa(int(me.Code))).Inc()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
c.opts.Meter.Counter(semconv.ClientRequestTotal, "endpoint", req.Endpoint(), "status", statusLabel, "code", strconv.Itoa(statusCode)).Inc()
|
||||||
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,3 +149,85 @@ func (c *Client) Stream(ctx context.Context, req client.Request, opts ...client.
|
|||||||
func (c *Client) String() string {
|
func (c *Client) String() string {
|
||||||
return "http"
|
return "http"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *Client) BatchPublish(ctx context.Context, ps []client.Message, opts ...client.PublishOption) error {
|
||||||
|
return c.funcBatchPublish(ctx, ps, opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) fnBatchPublish(ctx context.Context, ps []client.Message, opts ...client.PublishOption) error {
|
||||||
|
return c.publish(ctx, ps, opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) Publish(ctx context.Context, p client.Message, opts ...client.PublishOption) error {
|
||||||
|
return c.funcPublish(ctx, p, opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) fnPublish(ctx context.Context, p client.Message, opts ...client.PublishOption) error {
|
||||||
|
return c.publish(ctx, []client.Message{p}, opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) publish(ctx context.Context, ps []client.Message, opts ...client.PublishOption) error {
|
||||||
|
var body []byte
|
||||||
|
|
||||||
|
options := client.NewPublishOptions(opts...)
|
||||||
|
|
||||||
|
// get proxy
|
||||||
|
exchange := ""
|
||||||
|
if v, ok := os.LookupEnv("MICRO_PROXY"); ok {
|
||||||
|
exchange = v
|
||||||
|
}
|
||||||
|
// get the exchange
|
||||||
|
if len(options.Exchange) > 0 {
|
||||||
|
exchange = options.Exchange
|
||||||
|
}
|
||||||
|
|
||||||
|
msgs := make([]*broker.Message, 0, len(ps))
|
||||||
|
|
||||||
|
omd, ok := metadata.FromOutgoingContext(ctx)
|
||||||
|
if !ok {
|
||||||
|
omd = metadata.New(2)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, p := range ps {
|
||||||
|
md := metadata.Copy(omd)
|
||||||
|
topic := p.Topic()
|
||||||
|
if len(exchange) > 0 {
|
||||||
|
topic = exchange
|
||||||
|
}
|
||||||
|
md.Set(metadata.HeaderTopic, topic)
|
||||||
|
iter := p.Metadata().Iterator()
|
||||||
|
var k, v string
|
||||||
|
for iter.Next(&k, &v) {
|
||||||
|
md.Set(k, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
md[metadata.HeaderContentType] = p.ContentType()
|
||||||
|
|
||||||
|
// passed in raw data
|
||||||
|
if d, ok := p.Payload().(*codec.Frame); ok {
|
||||||
|
body = d.Data
|
||||||
|
} else {
|
||||||
|
// use codec for payload
|
||||||
|
cf, err := c.newCodec(p.ContentType())
|
||||||
|
if err != nil {
|
||||||
|
return errors.InternalServerError("go.micro.client", "%+v", err)
|
||||||
|
}
|
||||||
|
// set the body
|
||||||
|
b, err := cf.Marshal(p.Payload())
|
||||||
|
if err != nil {
|
||||||
|
return errors.InternalServerError("go.micro.client", "%+v", err)
|
||||||
|
}
|
||||||
|
body = b
|
||||||
|
}
|
||||||
|
msgs = append(msgs, &broker.Message{Header: md, Body: body})
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.opts.Broker.BatchPublish(ctx, msgs,
|
||||||
|
broker.PublishContext(options.Context),
|
||||||
|
broker.PublishBodyOnly(options.BodyOnly),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) NewMessage(topic string, msg interface{}, opts ...client.MessageOption) client.Message {
|
||||||
|
return newHTTPEvent(topic, msg, c.opts.ContentType, opts...)
|
||||||
|
}
|
||||||
|
|||||||
@@ -119,10 +119,23 @@ func buildHTTPRequest(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if log.V(logger.DebugLevel) {
|
if log.V(logger.DebugLevel) {
|
||||||
log.Debug(
|
if shouldLogBody(ct) {
|
||||||
ctx,
|
log.Debug(
|
||||||
fmt.Sprintf("request %s to %s with headers %v body %s", method, u.String(), hreq.Header, body),
|
ctx,
|
||||||
)
|
fmt.Sprintf(
|
||||||
|
"micro.client http request: method=%s url=%s headers=%v body=%s",
|
||||||
|
method, u.String(), hreq.Header, body,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
log.Debug(
|
||||||
|
ctx,
|
||||||
|
fmt.Sprintf(
|
||||||
|
"micro.client http request: method=%s url=%s headers=%v",
|
||||||
|
method, u.String(), hreq.Header,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return hreq, nil
|
return hreq, nil
|
||||||
@@ -259,3 +272,18 @@ func validateHeadersAndCookies(r *http.Request, parameters map[string]map[string
|
|||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func shouldLogBody(contentType string) bool {
|
||||||
|
ct := strings.ToLower(strings.Split(contentType, ";")[0])
|
||||||
|
switch {
|
||||||
|
case strings.HasPrefix(ct, "text/"): // => text/html, text/plain, text/csv etc.
|
||||||
|
return true
|
||||||
|
case ct == "application/json",
|
||||||
|
ct == "application/xml",
|
||||||
|
ct == "application/x-www-form-urlencoded",
|
||||||
|
ct == "application/yaml":
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -399,3 +399,49 @@ func TestValidateHeadersAndCookies(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestShouldLogBody(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
contentType string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
// --- text/*
|
||||||
|
{"plain text", "text/plain", true},
|
||||||
|
{"html", "text/html", true},
|
||||||
|
{"csv", "text/csv", true},
|
||||||
|
{"yaml text", "text/yaml", true},
|
||||||
|
|
||||||
|
// --- application/*
|
||||||
|
{"json", "application/json", true},
|
||||||
|
{"xml", "application/xml", true},
|
||||||
|
{"form-urlencoded", "application/x-www-form-urlencoded", true},
|
||||||
|
{"yaml", "application/yaml", true},
|
||||||
|
|
||||||
|
// --- with parameters
|
||||||
|
{"json with charset", "application/json; charset=utf-8", true},
|
||||||
|
{"binary with charset", "application/octet-stream; charset=utf-8", false},
|
||||||
|
|
||||||
|
// --- binary
|
||||||
|
{"multipart form", "multipart/form-data", false},
|
||||||
|
{"binary stream", "application/octet-stream", false},
|
||||||
|
{"pdf", "application/pdf", false},
|
||||||
|
{"protobuf", "application/protobuf", false},
|
||||||
|
{"image", "image/png", false},
|
||||||
|
|
||||||
|
// --- edge cases
|
||||||
|
{"upper case type", "APPLICATION/JSON", true},
|
||||||
|
{"mixed case type", "Text/HTML", true},
|
||||||
|
{"unknown text prefix", "TEXT/FOO", true},
|
||||||
|
{"weird semicolon only", ";", false},
|
||||||
|
{"spaces only", " ", false},
|
||||||
|
{"empty content-type", "", false},
|
||||||
|
{"missing main type", "/plain", false},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
require.Equal(t, tt.want, shouldLogBody(tt.contentType))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -207,8 +207,6 @@ func (c *Client) parseRsp(ctx context.Context, hrsp *http.Response, rsp any, opt
|
|||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
|
|
||||||
var buf []byte
|
|
||||||
|
|
||||||
if opts.ResponseMetadata != nil {
|
if opts.ResponseMetadata != nil {
|
||||||
for k, v := range hrsp.Header {
|
for k, v := range hrsp.Header {
|
||||||
opts.ResponseMetadata.Set(k, strings.Join(v, ","))
|
opts.ResponseMetadata.Set(k, strings.Join(v, ","))
|
||||||
@@ -224,6 +222,8 @@ func (c *Client) parseRsp(ctx context.Context, hrsp *http.Response, rsp any, opt
|
|||||||
ct = htype
|
ct = htype
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var buf []byte
|
||||||
|
|
||||||
if hrsp.Body != nil {
|
if hrsp.Body != nil {
|
||||||
var err error
|
var err error
|
||||||
buf, err = io.ReadAll(hrsp.Body)
|
buf, err = io.ReadAll(hrsp.Body)
|
||||||
@@ -232,15 +232,31 @@ func (c *Client) parseRsp(ctx context.Context, hrsp *http.Response, rsp any, opt
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if log.V(logger.DebugLevel) {
|
||||||
|
if shouldLogBody(ct) {
|
||||||
|
log.Debug(
|
||||||
|
ctx,
|
||||||
|
fmt.Sprintf(
|
||||||
|
"micro.client http response: status=%s headers=%v body=%s",
|
||||||
|
hrsp.Status, hrsp.Header, buf,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
log.Debug(
|
||||||
|
ctx,
|
||||||
|
fmt.Sprintf(
|
||||||
|
"micro.client http response: status=%s headers=%v",
|
||||||
|
hrsp.Status, hrsp.Header,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
cf, err := c.newCodec(ct)
|
cf, err := c.newCodec(ct)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.InternalServerError("go.micro.client", "unknown content-type %s: %v", ct, err)
|
return errors.InternalServerError("go.micro.client", "unknown content-type %s: %v", ct, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if log.V(logger.DebugLevel) {
|
|
||||||
log.Debug(ctx, fmt.Sprintf("response with headers: %v and body: %s", hrsp.Header, buf))
|
|
||||||
}
|
|
||||||
|
|
||||||
if hrsp.StatusCode < http.StatusBadRequest {
|
if hrsp.StatusCode < http.StatusBadRequest {
|
||||||
if err = cf.Unmarshal(buf, rsp); err != nil {
|
if err = cf.Unmarshal(buf, rsp); err != nil {
|
||||||
return errors.InternalServerError("go.micro.client", "unmarshal response: %v", err)
|
return errors.InternalServerError("go.micro.client", "unmarshal response: %v", err)
|
||||||
|
|||||||
44
message.go
Normal file
44
message.go
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
package http
|
||||||
|
|
||||||
|
import (
|
||||||
|
"go.unistack.org/micro/v3/client"
|
||||||
|
"go.unistack.org/micro/v3/metadata"
|
||||||
|
)
|
||||||
|
|
||||||
|
type httpEvent struct {
|
||||||
|
payload interface{}
|
||||||
|
topic string
|
||||||
|
contentType string
|
||||||
|
opts client.MessageOptions
|
||||||
|
}
|
||||||
|
|
||||||
|
func newHTTPEvent(topic string, payload interface{}, contentType string, opts ...client.MessageOption) client.Message {
|
||||||
|
options := client.NewMessageOptions(opts...)
|
||||||
|
|
||||||
|
if len(options.ContentType) > 0 {
|
||||||
|
contentType = options.ContentType
|
||||||
|
}
|
||||||
|
|
||||||
|
return &httpEvent{
|
||||||
|
payload: payload,
|
||||||
|
topic: topic,
|
||||||
|
contentType: contentType,
|
||||||
|
opts: options,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *httpEvent) ContentType() string {
|
||||||
|
return c.contentType
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *httpEvent) Topic() string {
|
||||||
|
return c.topic
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *httpEvent) Payload() interface{} {
|
||||||
|
return c.payload
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *httpEvent) Metadata() metadata.Metadata {
|
||||||
|
return c.opts.Metadata
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user