Skip to content

Commit

Permalink
新增curl命令解析
Browse files Browse the repository at this point in the history
  • Loading branch information
2kil committed Jun 26, 2024
1 parent d1a6e3f commit 5bb5d49
Showing 1 changed file with 91 additions and 1 deletion.
92 changes: 91 additions & 1 deletion 2kStar.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@
* @Author: 2Kil
* @Date: 2024-04-19 10:54:20
* @LastEditors: 2Kil
* @LastEditTime: 2024-05-29 12:41:28
* @LastEditTime: 2024-06-26 15:25:28
* @Description:tktar
*/
package tkstar

import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
Expand All @@ -18,9 +19,12 @@ import (
"log"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"sync/atomic"
"time"
Expand Down Expand Up @@ -228,3 +232,89 @@ func SysGetSerialKey() string {
// 简化设备码
return reg0[8:11] + reg0[2:3] + reg0[12:14]
}

/**
* @description:go的curl实现
* @param {string} cUrl(bash)格式的请求命令
* @return {*} 响应体
*/
func NetCurl(curlBash string) (int, string) {
// 解析curl命令
method, url, headers, data, err := NetParseCurlComd(curlBash)
if err != nil {
fmt.Println("Error parsing curl command:", err)
return 0, ""
}

// 创建一个HTTP POST请求
req, err := http.NewRequest(method, url, bytes.NewBuffer(data))
if err != nil {
fmt.Println("Error creating HTTP request:", err)
return 0, ""
}

// 设置HTTP头
req.Header = headers

// 如果你的数据体是JSON,并且你还没有设置Content-Type头,你可以在这里添加它
// req.Header.Set("Content-Type", "application/json")

// 发送HTTP请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("Error sending HTTP request:", err)
return 0, ""
}
defer resp.Body.Close()

// 读取并打印响应体
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Println("Error reading response body:", err)
return 0, ""
}
return resp.StatusCode, string(body)
}

/**
* @description: 解析curl命令
* @param {string} curlCmd
* @return {*} 请求方法,请求地址,请求头,请求体,错误信息
*/
func NetParseCurlComd(curlCmd string) (string, string, http.Header, []byte, error) {
// 提取URL
urlRe := regexp.MustCompile(`curl '([^']+)'`)
urlMatch := urlRe.FindStringSubmatch(curlCmd)
if len(urlMatch) != 2 {
return "GET", "", nil, nil, fmt.Errorf("failed to find URL in curl command")
}
rawURL := urlMatch[1]
parsedURL, err := url.Parse(rawURL)
if err != nil {
return "GET", "", nil, nil, err
}

// 提取HTTP头
headerRe := regexp.MustCompile(`-H '([^']+): ([^']+)'`)
headers := make(http.Header)
matches := headerRe.FindAllStringSubmatch(curlCmd, -1)
for _, match := range matches {
if len(match) != 3 {
continue
}
key, value := match[1], match[2]
headers.Set(key, value)
}

// 提取POST数据体
dataRe := regexp.MustCompile(`--data-raw '([^']+)'`)
dataMatch := dataRe.FindStringSubmatch(curlCmd)
if len(dataMatch) != 2 {
// 如果没有找到--data-raw,则假设是一个GET请求,并返回空的数据体
return "GET", parsedURL.String(), headers, nil, nil
}
rawData := []byte(dataMatch[1])

return "POST", parsedURL.String(), headers, rawData, nil
}

0 comments on commit 5bb5d49

Please sign in to comment.