You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

146 lines
3.1 KiB

package jsruntime
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
func (jr *JsRuntime) EnableRequestFunc() {
jr.runtime.Set("GoRequest", func(call map[string]interface{}) (respData string) {
url := ""
if call["url"] != nil {
url = call["url"].(string)
}
data := ""
if call["data"] != nil {
data = call["data"].(string)
}
header := map[string]interface{}{}
if call["header"] != nil {
header = call["header"].(map[string]interface{})
}
timeout := 0
if call["timeout"] != nil {
switch call["timeout"].(type) {
case int64:
timeout = int(call["timeout"].(int64))
case int:
timeout = call["timeout"].(int)
}
}
method := "GET"
if call["method"] != nil {
method = call["method"].(string)
}
client := &http.Client{
Timeout: time.Millisecond * time.Duration(timeout),
}
var contentReader *bytes.Reader
contentReader = bytes.NewReader([]byte(data))
//log.Println(method, url, data)
req, err := http.NewRequest(method, url, contentReader)
if err != nil {
rs, _ := json.Marshal(map[string]interface{}{
"statusCode": 504,
"data": err.Error(),
})
return string(rs)
}
for e := range header {
req.Header.Set(e, header[e].(string))
}
resp, err := client.Do(req)
var statusCode int
var respDatas string
if err == nil {
defer resp.Body.Close()
statusCode = resp.StatusCode
rb, _ := ioutil.ReadAll(resp.Body)
respDatas = string(rb)
} else {
statusCode = 502
respDatas = err.Error()
}
log2File("netword", "-------------------------------------------------")
log2File("netword", "网络请求:", method, url)
headerStr, _ := json.Marshal(header)
log2File("netword", "网络请求头:", string(headerStr))
log2File("netword", "网络请求发送数据:", data)
log2File("netword", "请求返回状态:", err == nil)
log2File("netword", "请求返回状态码:", statusCode)
log2File("netword", "请求返回:", respDatas)
log2File("netword", "-------------------------------------------------")
rs, _ := json.Marshal(map[string]interface{}{
"statusCode": statusCode,
"data": string(respDatas),
})
return string(rs)
})
}
func log2File(tag string, strs ...interface{}) {
str := fmt.Sprintln(strs...)
path := filepath.Join(getSelfFilePath(), fmt.Sprintf("jsruntime-%s.log", tag))
if pathExists(path) {
raw, _ := ioutil.ReadFile(path)
str = string(raw) + str
}
ioutil.WriteFile(path, []byte(str), 0644)
}
func pathExists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return false
}
var selfFilePath string
func getSelfFilePath() string {
if selfFilePath == "" {
file, err := exec.LookPath(os.Args[0])
if err != nil {
return ""
}
path, err := filepath.Abs(file)
if err != nil {
return ""
}
i := strings.LastIndex(path, "/")
if i < 0 {
i = strings.LastIndex(path, "\\")
}
if i < 0 {
return ""
}
selfFilePath, _ = filepath.Abs(string(path[0 : i+1]))
}
return selfFilePath
}