Module is introduced

Httpclient is a Go HTTP client request package encapsulated in NET/HTTP. It supports common request modes and common Settings, such as:

  • Support for setting Mock information
  • Support setting failure alarm
  • Retry when setting fails
  • Support for setting Trace within a project
  • You can set timeout period and Header

Request instructions

The method name describe
httpclient.Get() A GET request
httpclient.PostForm() POST request, form form
httpclient.PostJSON() POST request in json format
httpclient.PutForm() PUT request, form form
httpclient.PutJSON() PUT request in json format
httpclient.PatchForm() PATCH request in form format
httpclient.PatchJSON() PATCH request in json format
httpclient.Delete() The DELETE request

Configuration instructions

Configuration items Configuration method
TTL Sets the maximum timeout period of the request httpclient.WithTTL(ttl time.Duration)
Setting Header Information httpclient.WithHeader(key, value string)
Setting Logger Information httpclient.WithLogger(logger *zap.Logger)
Setting Trace Information httpclient.WithTrace(t trace.T)
Setting Mock Information httpclient.WithMock(m Mock)
This alarm is generated when the setting fails httpclient.WithOnFailedAlarm(alarmTitle string, alarmObject AlarmObject, alarmVerify AlarmVerify)
Retry if the setting fails httpclient.WithOnFailedRetry(retryTimes int, retryDelay time.Duration, retryVerify RetryVerify)

Set the TTL

// Set the maximum timeout period for this request to 5s
httpclient.WithTTL(time.Second*5),
Copy the code

Setting Header Information

You can call multiple key-value pairs to set them.

// Set multiple key-value pairs, for example:
httpclient.WithHeader("Authorization"."xxxx"),
httpclient.WithHeader("Date"."xxxx"),
Copy the code

Setting Logger Information

The passed Logger makes it easy for HttpClient to print logs.

// Use a logger in context like this:
httpclient.WithLogger(ctx.Logger()),
Copy the code

Setting Trace Information

The passed trace facilitates logging of links that call third-party interfaces using HttpClient.

// Use trace in context, for example:
httpclient.WithTrace(ctx.Trace()),
Copy the code

Setting Mock Information

/ / the Mock type
type Mock func(a) (body []byte)

// Implement a Mock method like this:
func MockDemoPost(a) (body []byte) {
	res := new(demoPostResponse)
	res.Code = 1
	res.Msg = "ok"
	res.Data.Name = "mock_Name"
	res.Data.Job = "mock_Job"

	body, _ = json.Marshal(res)
	return body
}

// When used:
httpclient.WithMock(MockDemoPost),
Copy the code

Passing Mock makes it easy to set up Mock data that calls third-party interfaces. As long as the interface document is agreed, even if the other interface is not developed, it does not affect the data synchronization.

This alarm is generated when the setting fails

// alarmTitle alarmTitle String

// AlarmObject Alarm notification object, which can be email, SMS, or wechat
type AlarmObject interface {
	Send(subject, body string) error
}

// You need to implement the AlarmObject interface, for example:
var _ httpclient.AlarmObject = (*AlarmEmail)(nil)

type AlarmEmail struct{}

func (a *AlarmEmail) Send(subject, body string) error {
	options := &mail.Options{
		MailHost: "smtp.163.com",
		MailPort: 465,
		MailUser: "[email protected]",
		MailPass: "",
		MailTo:   "",
		Subject:  subject,
		Body:     body,
	}
	return mail.Send(options)
}

// AlarmVerify Defines the verification rule that matches an alarm
type AlarmVerify func(body []byte) (shouldAlarm bool)

// The AlarmVerify method needs to be implemented, for example:
func alarmVerify(body []byte) (shouldalarm bool) {
	if len(body) == 0 {
		return true
	}

	type Response struct {
		Code int `json:"code"`
	}
	resp := new(Response)
	iferr := json.Unmarshal(body, resp); err ! =nil {
		return true
	}

    // An alarm is generated when the code returned by the third-party interface is not equal to the agreed success value (1)
	returnresp.Code ! =1
}

// When used:
httpclient.WithOnFailedAlarm("Interface Alarm".new(third_party_request.AlarmEmail), alarmVerify),
Copy the code

Retry if the setting fails

// retryTimes specifies the retryTimes Int. The default value is 3

// retryDelay Sets the delay time before retry time.Duration (default: time.millisecond * 100)

// RetryVerify Defines validation rules that conform to retries
type RetryVerify func(body []byte) (shouldRetry bool)

// The RetryVerify method needs to be implemented, for example:
func retryVerify(body []byte) (shouldRetry bool) {
	if len(body) == 0 {
		return true
	}

	type Response struct {
		Code int `json:"code"`
	}
	resp := new(Response)
	iferr := json.Unmarshal(body, resp); err ! =nil {
		return true
	}

    // When the third-party interface returns code equal to the convention value (10010), retry is required
	return resp.Code = 10010
}

// RetryVerify can also be nil. When nil, the default retry rule is http_code as follows:
// http.StatusRequestTimeout, 408
// http.StatusLocked, 423
// http.StatusTooEarly, 425
// http.StatusTooManyRequests, 429
// http.StatusServiceUnavailable, 503
// http.StatusGatewayTimeout, 504

// When used:
httpclient.WithOnFailedRetry(3, time.Second*1, retryVerify),
Copy the code

The sample code

// Take httpClient.postform as an example

api := "http://127.0.0.1:9999/demo/post"
params := url.Values{}
params.Set("name", name)
body, err := httpclient.PostForm(api, params,
	httpclient.WithTTL(time.Second*5),
	httpclient.WithTrace(ctx.Trace()),
	httpclient.WithLogger(ctx.Logger()),
	httpclient.WithHeader("Authorization"."xxxx"),
	httpclient.WithMock(MockDemoPost),
    httpclient.WithOnFailedRetry(3, time.Second*1, retryVerify),
    httpclient.WithOnFailedAlarm("Interface Alarm".new(third_party_request.AlarmEmail), alarmVerify),                             
)

iferr ! =nil {
    return nil, err
}

res = new(demoPostResponse)
err = json.Unmarshal(body, res)
iferr ! =nil {
    return nil, errors.Wrap(err, "DemoPost json unmarshal error")}ifres.Code ! =1 {
    return nil, errors.New(fmt.Sprintf("code err: %d-%s", res.Code, res.Msg))
}

return res, nil
Copy the code

The above code is in the Go-Gin-API project at github.com/xinliangnot…