mindxdl--common--http_handler.go
// Copyright (c) 2021. Huawei Technologies Co., Ltd. All rights reserved.
// Package common this file for send internal http request
package common
import (
"encoding/json"
"io/ioutil"
"net/http"
"strings"
"time"
)
// HTTPHandler send inner request
type HTTPHandler struct {
Client *http.Client
}
// Get get
func (handler *HTTPHandler) Get(url, params string, header map[string]string,
timeOut time.Duration) (*ResultMsg, error) {
return handler.sendRequest(http.MethodGet, url, params, header, timeOut)
}
// Post post
func (handler *HTTPHandler) Post(url, params string, header map[string]string,
timeOut time.Duration) (*ResultMsg, error) {
return handler.sendRequest(http.MethodPost, url, params, header, timeOut)
}
// Delete delete
func (handler *HTTPHandler) Delete(url, params string, header map[string]string,
timeOut time.Duration) (*ResultMsg, error) {
return handler.sendRequest(http.MethodDelete, url, params, header, timeOut)
}
// SetHeader SetHeader
func (handler *HTTPHandler) SetHeader(req *http.Request, header map[string]string) {
if header == nil || req == nil {
return
}
for key, val := range header {
req.Header.Set(key, val)
}
}
// NewRequest NewRequest
func (handler *HTTPHandler) NewRequest(method, url, params string) (*http.Request, error) {
if params != "" {
return http.NewRequest(method, url, strings.NewReader(params))
}
return http.NewRequest(method, url, nil)
}
func (handler *HTTPHandler) sendRequest(method, url, params string, header map[string]string,
timeOut time.Duration) (*ResultMsg, error) {
req, err := handler.NewRequest(method, url, params)
if err != nil {
return nil, err
}
handler.SetHeader(req, header)
handler.Client.Timeout = timeOut
resp, err := handler.Client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
responseBody, err := ioutil.ReadAll(resp.Body)
responseData := ResultMsg{}
if err = json.Unmarshal(responseBody, &responseData); err != nil {
return nil, err
}
return &responseData, nil
}
本文来自博客园,作者:易先讯,转载请注明原文链接:https://www.cnblogs.com/gongxianjin/p/16683166.html