Files
go-flash/core/http.go
2024-08-05 12:06:31 +08:00

86 lines
2.2 KiB
Go

package core
import (
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
var ApiUrl = "https://www.shuote.top:8082/flash/activity/applyActivity"
var Headers = map[string]string{
"Host": "www.shuote.top:8082",
"Connection": "keep-alive",
"Request-Channel": "MP-WEIXIN",
"X-Access-Token": "",
"Accept-Encoding": "gzip,compress,br,deflate",
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.49(0x18003137) NetType/WIFI Language/zh_CN",
"Referer": "https://servicewechat.com/wxbb50595cab69d719/403/page-frame.html",
}
// PostStruct 结构
type PostStruct struct {
PayAmount float64 `json:"payAmount"`
ActivityID int `json:"activityId"`
MaleCount int `json:"maleCount"`
FemaleCount int `json:"femaleCount"`
PayType int `json:"payType"`
GroupID int `json:"groupId"`
XbSex any `json:"xbSex"`
CardType int `json:"cardType"`
}
func ApiRequest(url string, customHeaders map[string]string, postData *PostStruct) (string, error) {
if url == "" {
return "", fmt.Errorf("URL is empty")
}
jsonData, err := json.Marshal(postData)
if err != nil {
return "", err
}
client := &http.Client{
Timeout: 30 * time.Second,
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return "", err
}
// 设置默认请求头
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Content-Length", fmt.Sprintf("%d", len(jsonData)))
// 如果有自定义请求头,则设置请求头
for key, value := range customHeaders {
req.Header.Set(key, value)
}
// 设置Accept-Encoding以接收压缩响应
req.Header.Set("Accept-Encoding", "gzip")
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
var reader io.ReadCloser
switch resp.Header.Get("Content-Encoding") {
case "gzip":
reader, err = gzip.NewReader(resp.Body)
if err != nil {
return "", err
}
defer reader.Close()
default:
reader = resp.Body
}
responseBytes, err := io.ReadAll(reader)
if err != nil {
return "", err
}
return string(responseBytes), nil
}