Skip to content

Commit

Permalink
feat: add api caller timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
withchao committed Oct 25, 2023
1 parent 02acbfe commit fd9b622
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion pkg/common/apicall/call.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"errors"
"io"
"net/http"
"time"

"github.com/OpenIMSDK/chat/pkg/common/constant"
constant2 "github.com/OpenIMSDK/protocol/constant"
Expand All @@ -36,6 +37,10 @@ type baseApiResponse[T any] struct {
Data *T `json:"data"`
}

var client = &http.Client{
Timeout: time.Second * 20,
}

type ApiCaller[Req, Resp any] interface {
Call(ctx context.Context, req *Req) (*Resp, error)
}
Expand Down Expand Up @@ -64,6 +69,10 @@ func (a caller[Req, Resp]) Call(ctx context.Context, req *Req) (*Resp, error) {

func (a caller[Req, Resp]) call(ctx context.Context, req *Req) (*Resp, error) {
url := a.prefix() + a.api
start := time.Now()
defer func() {
log.ZDebug(ctx, "call caller", "api", a.api, "cost", time.Since(start))
}()
log.ZInfo(ctx, "caller req", "addr", url, "req", req)
reqBody, err := json.Marshal(req)
if err != nil {
Expand All @@ -79,7 +88,7 @@ func (a caller[Req, Resp]) call(ctx context.Context, req *Req) (*Resp, error) {
request.Header.Set(constant2.Token, token)
log.ZDebug(ctx, "req token", "token", token)
}
response, err := http.DefaultClient.Do(request)
response, err := client.Do(request)
if err != nil {
return nil, err
}
Expand Down

0 comments on commit fd9b622

Please sign in to comment.