Jelajahi Sumber

add webuitls

tl 2 tahun lalu
induk
melakukan
c5f1363b16
6 mengubah file dengan 279 tambahan dan 0 penghapusan
  1. 3 0
      go.mod
  2. 72 0
      webutils/http.go
  3. 53 0
      webutils/http_test.go
  4. 46 0
      webutils/http_utils.go
  5. 28 0
      webutils/ip.go
  6. 77 0
      webutils/response.go

+ 3 - 0
go.mod

@@ -0,0 +1,3 @@
+module pkg.daxia.dev
+
+go 1.18

+ 72 - 0
webutils/http.go

@@ -0,0 +1,72 @@
+package webutils
+
+import (
+	"errors"
+	"io"
+	"net/http"
+	"strings"
+	"time"
+
+	"github.com/sirupsen/logrus"
+)
+
+func Get(reqUrl string, timeout time.Duration) ([]byte, error) {
+	req, err := http.NewRequest(http.MethodGet, reqUrl, nil)
+	if err != nil {
+		logrus.Error(err)
+		return nil, err
+	}
+
+	cli := http.Client{
+		Timeout: timeout,
+	}
+
+	resp, err := cli.Do(req)
+	if err != nil {
+		logrus.Error(err)
+		return nil, err
+	}
+
+	defer resp.Body.Close()
+
+	b, err := io.ReadAll(resp.Body)
+	if err != nil {
+		logrus.Error(err)
+		return nil, err
+	}
+
+	return b, nil
+}
+
+func Post(reqUrl string, payload string, timeout time.Duration) ([]byte, error) {
+	req, err := http.NewRequest(http.MethodPost, reqUrl, strings.NewReader(payload))
+	if err != nil {
+		logrus.Error(err)
+		return nil, err
+	}
+
+	cli := http.Client{
+		Timeout: timeout,
+	}
+
+	resp, err := cli.Do(req)
+	if err != nil {
+		logrus.Error(err)
+		return nil, err
+	}
+
+	if resp.StatusCode != http.StatusOK {
+		logrus.Error("状态码错误:", resp)
+		return nil, errors.New("状态码错误")
+	}
+
+	defer resp.Body.Close()
+
+	b, err := io.ReadAll(resp.Body)
+	if err != nil {
+		logrus.Error(err)
+		return nil, err
+	}
+
+	return b, nil
+}

+ 53 - 0
webutils/http_test.go

@@ -0,0 +1,53 @@
+package webutils
+
+import (
+	"encoding/json"
+	"fmt"
+	"testing"
+	"time"
+
+	"github.com/stretchr/testify/assert"
+)
+
+func TestGet(t *testing.T) {
+	resp, err := Get("https://ip.sb", time.Second*3)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	assert.NotEmpty(t, resp)
+}
+
+func TestPostJson(t *testing.T) {
+	type ReqData struct {
+		Username string
+	}
+
+	reqData := ReqData{
+		Username: "123",
+	}
+
+	dataByte, _ := json.Marshal(reqData)
+
+	_, err := Post("https://ip.sb", string(dataByte), time.Second*3)
+	assert.Error(t, err)
+}
+
+func TestGetResp(t *testing.T) {
+	type DataItem struct {
+		API  string   `json:"api"`
+		V    string   `json:"v"`
+		Ret  []string `json:"ret"`
+		Data struct {
+			T string `json:"t"`
+		} `json:"data"`
+	}
+
+	reqUrl := "http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp"
+	resp, err := GetResp[DataItem](reqUrl, time.Second*3)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	fmt.Println(resp)
+}

+ 46 - 0
webutils/http_utils.go

@@ -0,0 +1,46 @@
+package webutils
+
+import (
+	"encoding/json"
+	"time"
+
+	"github.com/sirupsen/logrus"
+)
+
+func GetResp[T interface{}](reqUrl string, timeout time.Duration) (*ResponseGen[T], error) {
+	logrus.Info("request, url:", reqUrl)
+
+	resp, err := Get(reqUrl, timeout)
+	if err != nil {
+		return nil, err
+	}
+
+	respData := ResponseGen[T]{}
+	err = json.Unmarshal([]byte(resp), &respData)
+	if err != nil {
+		return nil, err
+	}
+
+	logrus.Info("response: url: ", reqUrl, " body:", respData)
+
+	return &respData, nil
+}
+
+func PostResp[T interface{}](reqUrl string, payload string, timeout time.Duration) (*ResponseGen[T], error) {
+	logrus.Info("request, url:", reqUrl, " payload:", payload)
+
+	resp, err := Post(reqUrl, payload, timeout)
+	if err != nil {
+		return nil, err
+	}
+
+	respData := ResponseGen[T]{}
+	err = json.Unmarshal([]byte(resp), &respData)
+	if err != nil {
+		return nil, err
+	}
+
+	logrus.Info("response: url: ", reqUrl, " body:", respData)
+
+	return &respData, nil
+}

+ 28 - 0
webutils/ip.go

@@ -0,0 +1,28 @@
+package webutils
+
+import (
+	"net"
+	"net/http"
+	"strings"
+)
+
+func ClientIP(r *http.Request, useCDN bool) string {
+	if useCDN {
+		xForwardedFor := r.Header.Get("X-Forwarded-For")
+		ip := strings.TrimSpace(strings.Split(xForwardedFor, ",")[0])
+		if ip != "" {
+			return ip
+		}
+
+		ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
+		if ip != "" {
+			return ip
+		}
+	}
+
+	if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
+		return ip
+	}
+
+	return ""
+}

+ 77 - 0
webutils/response.go

@@ -0,0 +1,77 @@
+package webutils
+
+import (
+	"net/http"
+
+	"daxia.dev/internal/dxpay/kkerror"
+	"github.com/gin-gonic/gin"
+	ut "github.com/go-playground/universal-translator"
+	"github.com/sirupsen/logrus"
+)
+
+const (
+	CodeSuccess      = 20000
+	CodeFailed       = -1
+	CodeIllegalToken = 50008
+	CodeTokenExpired = 50014
+	CodeOther        = 50012
+)
+
+var (
+	trans ut.Translator
+)
+
+type Response struct {
+	Code int         `json:"code"`
+	Msg  string      `json:"msg"`
+	Data interface{} `json:"data"`
+}
+
+type ResponseGen[T interface{}] struct {
+	Code int    `json:"code"`
+	Msg  string `json:"msg"`
+	Data T      `json:"data"`
+}
+
+func FailedResponse(c *gin.Context, msg string) {
+	if c == nil {
+		return
+	}
+
+	c.JSON(http.StatusOK, &Response{
+		Code: CodeFailed,
+		Msg:  msg,
+		Data: nil,
+	})
+
+	panic(kkerror.NewRespError("failed"))
+}
+
+func FailedResponseErr(c *gin.Context, err error) {
+	if c == nil {
+		return
+	}
+
+	logrus.Error(err)
+	FailedResponse(c, "内部错误")
+}
+
+func FailedResponseWithCode(c *gin.Context, code int, msg string) {
+	c.JSON(http.StatusOK, &Response{
+		Code: code,
+		Msg:  msg,
+		Data: nil,
+	})
+
+	panic(kkerror.NewRespError("failed"))
+}
+
+func SuccessResponse(c *gin.Context, data interface{}) {
+	c.JSON(http.StatusOK, &Response{
+		Code: CodeSuccess,
+		Msg:  "",
+		Data: data,
+	})
+
+	panic(kkerror.NewRespError("success"))
+}