heritage-api/service/base-service.go

97 lines
2.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package service
import (
"bytes"
"io"
"net/http"
"strings"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
)
func newID() string {
i := uuid.Must(uuid.NewUUID()).String()
return strings.ReplaceAll(i, "-", "")
}
// 专用给创建新用户的ID32位
func newUserID() string {
i := uuid.Must(uuid.NewV7()).String()
return strings.ReplaceAll(i, "-", "")
}
// 专给机构创建用的ID20位
func newOrgID() string {
i := uuid.Must(uuid.NewV7()).String()
return strings.ReplaceAll(i, "-", "")[12:]
}
// 项目ID22位
func newProjectID() string {
i := uuid.Must(uuid.NewV7()).String()
return strings.ReplaceAll(i, "-", "")[10:]
}
func newToken() string {
i := uuid.Must(uuid.NewUUID()).String()
return strings.ReplaceAll(i, "-", "")
}
// httpDO 通用的HTTP请求函数
func httpDO(url, method string, headers map[string]string, body []byte) ([]byte, error) {
var reqBody io.Reader
if body != nil {
reqBody = bytes.NewBuffer(body)
}
req, err := http.NewRequest(method, url, reqBody)
if err != nil {
logrus.WithFields(logrus.Fields{
"func": "httpDO",
"url": url,
"method": method,
}).Errorf("http.NewRequest: %v", err)
return nil, err
}
for k, v := range headers {
req.Header.Set(k, v)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
logrus.WithFields(logrus.Fields{
"func": "httpDO",
"url": url,
"method": method,
}).Errorf("client.Do failed: %v", err)
return nil, err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
logrus.WithFields(logrus.Fields{
"func": "httpDO",
"url": url,
"method": method,
}).Errorf("io.ReadAll failed: %v", err)
return nil, err
}
if resp.StatusCode >= 400 {
logrus.WithFields(logrus.Fields{
"func": "httpDO",
"url": url,
"method": method,
"statusCode": resp.StatusCode,
"response": string(respBody),
}).Errorf("HTTP request failed with status code: %d", resp.StatusCode)
return respBody, err
}
return respBody, nil
}