Skip to content

Commit

Permalink
feat: bce bos support request context
Browse files Browse the repository at this point in the history
modify http.Execute and http.Request support set context, all bos method add same method with suffix WithContext, and the first parameter is context.

Resolves baidubce#81
  • Loading branch information
haormj committed Apr 4, 2023
1 parent 8e1d743 commit 8613923
Show file tree
Hide file tree
Showing 5 changed files with 1,075 additions and 41 deletions.
31 changes: 16 additions & 15 deletions http/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,26 +106,27 @@ func InitClient(config ClientConfig) {
// - response: the http response returned from the server
// - error: nil if ok otherwise the specific error
func Execute(request *Request) (*Response, error) {
// Build the request object for the current requesting
httpRequest := &http.Request{
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
}

// Set the connection timeout for current request
httpClient.Timeout = time.Duration(request.Timeout()) * time.Second

// Set the request method
httpRequest.Method = request.Method()

// Set the request url
internalUrl := &url.URL{
Scheme: request.Protocol(),
Host: request.Host(),
Path: request.Uri(),
RawQuery: request.QueryString()}
httpRequest.URL = internalUrl
RawQuery: request.QueryString(),
}

// Build the request object for the current requesting
httpRequest, err := http.NewRequestWithContext(
request.Context(),
request.Method(),
internalUrl.String(),
nil,
)
if err != nil {
return nil, err
}

// Set the connection timeout for current request
httpClient.Timeout = time.Duration(request.Timeout()) * time.Second

// Set the request headers
internalHeader := make(http.Header)
Expand Down
14 changes: 14 additions & 0 deletions http/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package http

import (
"context"
"fmt"
"io"
"strconv"
Expand All @@ -40,6 +41,8 @@ type Request struct {
// Optional body and length fields to set the body stream and content length
body io.ReadCloser
length int64

ctx context.Context
}

func (r *Request) Protocol() string {
Expand Down Expand Up @@ -211,6 +214,17 @@ func (r *Request) GenerateUrl(addPort bool) string {
}
}

func (r *Request) Context() context.Context {
if r.ctx != nil {
return r.ctx
}
return context.Background()
}

func (r *Request) SetContext(ctx context.Context) {
r.ctx = ctx
}

func (r *Request) String() string {
header := make([]string, 0, len(r.headers))
for k, v := range r.headers {
Expand Down
Loading

0 comments on commit 8613923

Please sign in to comment.