79 lines
2.1 KiB
Go
79 lines
2.1 KiB
Go
|
|
// Package network define struct of network operation
|
|||
|
|
package network
|
|||
|
|
|
|||
|
|
import (
|
|||
|
|
"fmt"
|
|||
|
|
"io"
|
|||
|
|
"net/http"
|
|||
|
|
"strings"
|
|||
|
|
"time"
|
|||
|
|
|
|||
|
|
"modelRT/logger"
|
|||
|
|
|
|||
|
|
"go.uber.org/zap"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
// APIEndpoint defines an api endpoint struct to poll data from dataRT service
|
|||
|
|
type APIEndpoint struct {
|
|||
|
|
URL string `json:"url"`
|
|||
|
|
Method string `json:"method"` // HTTP 方法,如 "GET", "POST"
|
|||
|
|
Headers map[string]string `json:"headers"`
|
|||
|
|
QueryParams map[string]string `json:"query_params"`
|
|||
|
|
Body string `json:"body"` // 对于 POST 请求需要一个请求体
|
|||
|
|
Interval int `json:"interval"` // 轮询间隔时间(秒)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// fetchAPI defines execute http request and return response or error
|
|||
|
|
func fetchAPI(endpoint APIEndpoint) (string, error) {
|
|||
|
|
client := &http.Client{}
|
|||
|
|
|
|||
|
|
req, err := http.NewRequest(endpoint.Method, endpoint.URL, nil)
|
|||
|
|
if err != nil {
|
|||
|
|
return "", err
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
for key, value := range endpoint.Headers {
|
|||
|
|
req.Header.Set(key, value)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
query := req.URL.Query()
|
|||
|
|
for key, value := range endpoint.QueryParams {
|
|||
|
|
query.Set(key, value)
|
|||
|
|
}
|
|||
|
|
req.URL.RawQuery = query.Encode()
|
|||
|
|
|
|||
|
|
if endpoint.Method == "POST" || endpoint.Method == "PUT" {
|
|||
|
|
req.Body = io.NopCloser(strings.NewReader(endpoint.Body))
|
|||
|
|
req.Header.Set("Content-Type", "application/json")
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
resp, err := client.Do(req)
|
|||
|
|
if err != nil {
|
|||
|
|
return "", err
|
|||
|
|
}
|
|||
|
|
defer resp.Body.Close()
|
|||
|
|
|
|||
|
|
body, err := io.ReadAll(resp.Body)
|
|||
|
|
if err != nil {
|
|||
|
|
return "", err
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return string(body), nil
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// pollAPIEndpoints defines unmarshal polling data from http request
|
|||
|
|
func pollAPIEndpoints(endpoint APIEndpoint) {
|
|||
|
|
logger := logger.GetLoggerInstance()
|
|||
|
|
|
|||
|
|
respStr, err := fetchAPI(endpoint)
|
|||
|
|
if err != nil {
|
|||
|
|
logger.Error("unmarshal component anchor point replace info failed", zap.Error(err))
|
|||
|
|
return
|
|||
|
|
}
|
|||
|
|
fmt.Println(respStr)
|
|||
|
|
time.Sleep(time.Duration(endpoint.Interval) * time.Second)
|
|||
|
|
// 注意:这里使用了 endpoint.Interval 而不是传入的 interval,
|
|||
|
|
// 但为了示例简单,我们统一使用传入的 interval。
|
|||
|
|
// 如果要根据每个端点的不同间隔来轮询,应该使用 endpoint.Interval。
|
|||
|
|
}
|