Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fe11fb8bcd | |||
|
|
7e554f2bbf | ||
| fa1a8af683 | |||
| 501f479a87 | |||
| 60979b12eb | |||
| 62bce65656 |
2
.github/workflows/job_sync.yml
vendored
2
.github/workflows/job_sync.yml
vendored
@@ -25,7 +25,7 @@ jobs:
|
|||||||
dst_hash=$(git ls-remote ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} refs/heads/master | cut -f1)
|
dst_hash=$(git ls-remote ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} refs/heads/master | cut -f1)
|
||||||
echo "src_hash=$src_hash"
|
echo "src_hash=$src_hash"
|
||||||
echo "dst_hash=$dst_hash"
|
echo "dst_hash=$dst_hash"
|
||||||
if [ "$src_hash" != "$dst_hash" ]; then
|
if [ "$src_hash" != "$dst_hash" -a "$src_hash" != "" -a "$dst_hash" != "" ]; then
|
||||||
echo "sync_needed=true" >> $GITHUB_OUTPUT
|
echo "sync_needed=true" >> $GITHUB_OUTPUT
|
||||||
else
|
else
|
||||||
echo "sync_needed=false" >> $GITHUB_OUTPUT
|
echo "sync_needed=false" >> $GITHUB_OUTPUT
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
# HTTP Client
|
# HTTP Client
|
||||||

|

|
||||||
|
|
||||||
This plugin is an HTTP client for [Micro](https://pkg.go.dev/go.unistack.org/micro/v4).
|
This plugin is an HTTP client for [Micro](https://pkg.go.dev/go.unistack.org/micro/v4).
|
||||||
It implements the [micro.Client](https://pkg.go.dev/go.unistack.org/micro/v4/client#Client) interface.
|
It implements the [micro.Client](https://pkg.go.dev/go.unistack.org/micro/v4/client#Client) interface.
|
||||||
|
|||||||
34
client.go
34
client.go
@@ -12,8 +12,12 @@ import (
|
|||||||
"go.unistack.org/micro/v4/options"
|
"go.unistack.org/micro/v4/options"
|
||||||
"go.unistack.org/micro/v4/semconv"
|
"go.unistack.org/micro/v4/semconv"
|
||||||
"go.unistack.org/micro/v4/tracer"
|
"go.unistack.org/micro/v4/tracer"
|
||||||
|
|
||||||
|
"go.unistack.org/micro-client-http/v4/status"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var _ client.Client = (*Client)(nil)
|
||||||
|
|
||||||
var DefaultContentType = "application/json"
|
var DefaultContentType = "application/json"
|
||||||
|
|
||||||
type Client struct {
|
type Client struct {
|
||||||
@@ -91,25 +95,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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -225,10 +238,10 @@ func applyCookies(r *http.Request, rawCookies []string) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
raw := strings.Join(rawCookies, "; ")
|
|
||||||
|
|
||||||
tmp := http.Request{Header: http.Header{}}
|
tmp := http.Request{Header: http.Header{}}
|
||||||
tmp.Header.Set("Cookie", raw)
|
for _, raw := range rawCookies {
|
||||||
|
tmp.Header.Add("Cookie", raw)
|
||||||
|
}
|
||||||
|
|
||||||
for _, c := range tmp.Cookies() {
|
for _, c := range tmp.Cookies() {
|
||||||
r.AddCookie(c)
|
r.AddCookie(c)
|
||||||
@@ -261,3 +274,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,11 +207,9 @@ 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.Append(k, 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)
|
||||||
|
|||||||
@@ -1186,6 +1186,98 @@ func TestClient_Call_HeadersAndCookies(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestClient_Call_SetCookie(t *testing.T) {
|
||||||
|
type (
|
||||||
|
request = pb.Test_Client_Call_Request
|
||||||
|
response = pb.Test_Client_Call_Response
|
||||||
|
)
|
||||||
|
|
||||||
|
serverMock := func() *httptest.Server {
|
||||||
|
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// Validate request
|
||||||
|
require.Equal(t, "POST", r.Method)
|
||||||
|
require.Equal(t, "/user/products", r.URL.RequestURI())
|
||||||
|
|
||||||
|
require.Equal(t, "application/json", r.Header.Get("Content-Type"))
|
||||||
|
require.Equal(t, "Bearer token", r.Header.Get("Authorization"))
|
||||||
|
require.Equal(t, "My-Header-Value", r.Header.Get("My-Header"))
|
||||||
|
|
||||||
|
buf, err := io.ReadAll(r.Body)
|
||||||
|
require.NoError(t, err)
|
||||||
|
defer r.Body.Close()
|
||||||
|
|
||||||
|
c := jsoncodec.NewCodec()
|
||||||
|
|
||||||
|
req := &request{}
|
||||||
|
err = c.Unmarshal(buf, req)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.True(t, proto.Equal(&request{UserId: "123", OrderId: 456}, req))
|
||||||
|
|
||||||
|
// Return response
|
||||||
|
cookieN1, err := http.ParseSetCookie("sessionid=abc123; Path=/; HttpOnly")
|
||||||
|
require.NoError(t, err)
|
||||||
|
http.SetCookie(w, cookieN1)
|
||||||
|
|
||||||
|
cookieN2, err := http.ParseSetCookie("theme=dark; Path=/; Max-Age=3600")
|
||||||
|
require.NoError(t, err)
|
||||||
|
http.SetCookie(w, cookieN2)
|
||||||
|
|
||||||
|
cookieN3, err := http.ParseSetCookie("lang=en-US; Path=/")
|
||||||
|
require.NoError(t, err)
|
||||||
|
http.SetCookie(w, cookieN3)
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.Header().Set("My-Header", "My-Header-Value")
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
server := serverMock()
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
httpClient := httpcli.NewClient(
|
||||||
|
client.Codec("application/json", jsoncodec.NewCodec()),
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ctx = metadata.NewOutgoingContext(
|
||||||
|
context.Background(),
|
||||||
|
metadata.Pairs("Authorization", "Bearer token", "My-Header", "My-Header-Value"),
|
||||||
|
)
|
||||||
|
req = &request{UserId: "123", OrderId: 456}
|
||||||
|
rsp = &response{}
|
||||||
|
|
||||||
|
respMetadata = metadata.Metadata{}
|
||||||
|
)
|
||||||
|
|
||||||
|
opts := []client.CallOption{
|
||||||
|
client.WithAddress(server.URL),
|
||||||
|
client.WithResponseMetadata(&respMetadata),
|
||||||
|
httpcli.Method(http.MethodPost),
|
||||||
|
httpcli.Path("/user/products"),
|
||||||
|
httpcli.Body("*"),
|
||||||
|
}
|
||||||
|
|
||||||
|
expectedSetCookie := []string{"sessionid=abc123; Path=/; HttpOnly", "theme=dark; Path=/; Max-Age=3600", "lang=en-US; Path=/"}
|
||||||
|
|
||||||
|
err := httpClient.Call(
|
||||||
|
ctx,
|
||||||
|
httpClient.NewRequest("test.service", "Test.Call", req),
|
||||||
|
rsp,
|
||||||
|
opts...,
|
||||||
|
)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Empty(t, rsp)
|
||||||
|
|
||||||
|
require.Equal(t, "application/json", respMetadata.GetJoined("Content-Type"))
|
||||||
|
require.Equal(t, "My-Header-Value", respMetadata.GetJoined("My-Header"))
|
||||||
|
for i, raw := range respMetadata.Get("Set-Cookie") {
|
||||||
|
cookie, err := http.ParseSetCookie(raw)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, expectedSetCookie[i], cookie.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestClient_Call_NoContent(t *testing.T) {
|
func TestClient_Call_NoContent(t *testing.T) {
|
||||||
type (
|
type (
|
||||||
request = pb.Test_Client_Call_Request
|
request = pb.Test_Client_Call_Request
|
||||||
|
|||||||
Reference in New Issue
Block a user