Skip to content

Commit

Permalink
feat: add response
Browse files Browse the repository at this point in the history
  • Loading branch information
ViolaPioggia committed May 14, 2024
1 parent f7ac4a6 commit 3c45281
Show file tree
Hide file tree
Showing 5 changed files with 264 additions and 8 deletions.
129 changes: 121 additions & 8 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,12 @@
package easy_http

import (
"context"
"github.com/cloudwego/hertz/pkg/protocol"
"net/http"
"net/url"
"sync"
"time"

"github.com/cloudwego/hertz/pkg/app/client"
)
Expand All @@ -29,17 +33,19 @@ type Client struct {
Header http.Header
Cookies []*http.Cookie

client *client.Client
}
beforeRequest []RequestMiddleware

Check failure on line 36 in client.go

View workflow job for this annotation

GitHub Actions / lint

field `beforeRequest` is unused (unused)
udBeforeRequest []RequestMiddleware

Check failure on line 37 in client.go

View workflow job for this annotation

GitHub Actions / lint

field `udBeforeRequest` is unused (unused)
afterResponse []ResponseMiddleware

Check failure on line 38 in client.go

View workflow job for this annotation

GitHub Actions / lint

field `afterResponse` is unused (unused)
afterResponseLock *sync.RWMutex

Check failure on line 39 in client.go

View workflow job for this annotation

GitHub Actions / lint

field `afterResponseLock` is unused (unused)
udBeforeRequestLock *sync.RWMutex

Check failure on line 40 in client.go

View workflow job for this annotation

GitHub Actions / lint

field `udBeforeRequestLock` is unused (unused)

func New() *Client {
c, _ := client.NewClient()
return &Client{client: c}
client *client.Client
}

func NewWithHertzClient(c *client.Client) *Client {
return createClient(c)
}
type (
RequestMiddleware func(*Client, *Request) error
ResponseMiddleware func(*Client, *Response) error
)

func createClient(c *client.Client) *Client {
return &Client{client: c}
Expand Down Expand Up @@ -67,6 +73,7 @@ func (c *Client) SetQueryParamsFromValues(params url.Values) *Client {
}

func (c *Client) SetQueryString(query string) *Client {
// todo: parse query string
return c
}

Expand Down Expand Up @@ -106,6 +113,15 @@ func (c *Client) SetHeaders(headers map[string]string) *Client {
return c
}

func (c *Client) SetHeaderMultiValues(headers map[string][]string) *Client {
for k, header := range headers {
for _, v := range header {
c.Header.Set(k, v)
}
}
return c
}

func (c *Client) AddHeader(header, value string) *Client {
c.Header.Add(header, value)
return c
Expand All @@ -118,6 +134,46 @@ func (c *Client) AddHeaders(headers map[string]string) *Client {
return c
}

func (c *Client) AddHeaderMultiValues(headers map[string][]string) *Client {
for k, header := range headers {
for _, v := range header {
c.Header.Add(k, v)
}
}
return c
}

func (c *Client) SetContentType(contentType string) *Client {
c.Header.Set("Content-Type", contentType)
return c
}

func (c *Client) SetJSONContentType() *Client {
c.Header.Set("Content-Type", "application/json")
return c
}

func (c *Client) SetXMLContentType() *Client {
c.Header.Set("Content-Type", "application/xml")
return c
}

func (c *Client) SetHTMLContentType() *Client {
c.Header.Set("Content-Type", "text/html")
return c
}

func (c *Client) SetFormContentType() *Client {
c.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return c

}

func (c *Client) SetXFormData() *Client {
c.Header.Set("Content-Type", "multipart/form-data")
return c
}

func (c *Client) SetCookie(hc *http.Cookie) *Client {
c.Cookies = append(c.Cookies, hc)
return c
Expand All @@ -143,3 +199,60 @@ func (c *Client) R() *Request {
func (c *Client) NewRequest() *Request {
return c.R()
}

func (c *Client) execute(req *Request) (*Response, error) {

Check failure on line 203 in client.go

View workflow job for this annotation

GitHub Actions / lint

func `(*Client).execute` is unused (unused)
// Lock the user-defined pre-request hooks.
c.udBeforeRequestLock.RLock()
defer c.udBeforeRequestLock.RUnlock()

// Lock the post-request hooks.
c.afterResponseLock.RLock()
defer c.afterResponseLock.RUnlock()

// Apply Request middleware
var err error

// user defined on before request methods
// to modify the *resty.Request object
for _, f := range c.udBeforeRequest {
if err = f(c, req); err != nil {
return nil, err
}
}

for _, f := range c.beforeRequest {
if err = f(c, req); err != nil {
return nil, err
}
}

if hostHeader := req.Header.Get("Host"); hostHeader != "" {
req.RawRequest.SetHost(hostHeader)
}

req.Time = time.Now()

resp := &protocol.Response{}
err = c.client.Do(context.Background(), req.RawRequest, resp)

response := &Response{
Request: req,
RawResponse: resp,
}

if err != nil {
response.receiveAt = time.Now()
return response, err
}

response.receiveAt = time.Now()

// Apply Response middleware
for _, f := range c.afterResponse {
if err = f(c, response); err != nil {
break
}
}

return response, err
}
36 changes: 36 additions & 0 deletions easy_http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Copyright 2024 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package easy_http

import "github.com/cloudwego/hertz/pkg/app/client"

func New() (*Client, error) {
c, err := client.NewClient()
return &Client{client: c}, err
}

func MustNew() *Client {
c, err := client.NewClient()
if err != nil {
panic(err)
}
return &Client{client: c}
}

func NewWithHertzClient(c *client.Client) *Client {
return createClient(c)
}
17 changes: 17 additions & 0 deletions middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
* Copyright 2024 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package easy_http
2 changes: 2 additions & 0 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"context"
"net/http"
"net/url"
"time"

"github.com/cloudwego/hertz/pkg/common/config"
"github.com/cloudwego/hertz/pkg/protocol"
Expand All @@ -37,6 +38,7 @@ type Request struct {
FileParams map[string]string
BodyParams interface{}
RawRequest *protocol.Request
Time time.Time
Ctx context.Context
RequestOptions []config.RequestOption
Result interface{}
Expand Down
88 changes: 88 additions & 0 deletions response.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* Copyright 2024 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package easy_http

import (
"github.com/cloudwego/hertz/pkg/protocol"
"strings"
"time"
)

type Response struct {
Request *Request // 上面的 Request 结构体
RawResponse *protocol.Response

receiveAt time.Time

Check failure on line 29 in response.go

View workflow job for this annotation

GitHub Actions / lint

field `receiveAt` is unused (unused)

bodyByte []byte
size int64

Check failure on line 32 in response.go

View workflow job for this annotation

GitHub Actions / lint

field `size` is unused (unused)
}

func (r *Response) Body() []byte {
if r.RawResponse == nil {
return []byte{}
}
return r.bodyByte
}

func (r *Response) BodyString() string {
if r.RawResponse == nil {
return ""
}
return strings.TrimSpace(string(r.bodyByte))
}

func (r *Response) StatusCode() int {
if r.RawResponse == nil {
return 0
}
return r.RawResponse.StatusCode()
}

func (r *Response) Result() interface{} {
return r.Request.Result
}

func (r *Response) Error() interface{} {
return r.Request.Error
}

// todo
//func (r *Response) Header() http.Header {
// if r.RawResponse == nil {
// return http.Header{}
// }
// return r.RawResponse.Header.GetHeaders()
//}
//
//func (r *Response) Cookies() []*http.Cookie {
// if r.RawResponse == nil {
// return make([]*http.Cookie, 0)
// }
// return r.RawResponse.Header.GetCookies()
//}
//func (r *Response) ToRawHTTPResponse() string {
// return r.RawResponse.String()
//}

func (r *Response) IsSuccess() bool {
return r.StatusCode() > 199 && r.StatusCode() < 300
}

func (r *Response) IsError() bool {
return r.StatusCode() > 399
}

0 comments on commit 3c45281

Please sign in to comment.