This commit is contained in:
cdle
2023-06-01 15:24:23 +08:00
parent 1ee28c45c4
commit 0432c2505b
9 changed files with 165 additions and 59 deletions
+4 -4
View File
@@ -7,7 +7,7 @@
- 简单易用的消息搬运功能。
- 简单强大的自定义回复功能。
- 完整支持 ECMAScript 5.1 的插件系统,基于 [otto](https://github.com/robertkrimen/otto)。
- 支持通过内置的阉割版 `Express` / `request` ,接入互联网。
- 支持通过内置的阉割版 `Express` / `fetch` ,接入互联网。
- 内置 `Cron` ,轻松实现定时任务。
- 持久化的 `Bucket` 存储模块。
- 支持同时接入多个平台多个机器人,自己开发。
@@ -181,7 +181,7 @@ app.post(api, (req, res) => res.json(req.json()));
//第二步,请求第一步实现的接口
const port = Bucket("app").port ?? "8080"; // 获取http服务端口
const url = `http://127.0.0.1:${port}${api}`;
request({
fetch({
url,
method: "POST",
body: { value: "test" },
@@ -345,12 +345,12 @@ interface Response {
}
```
### request
### fetch
`net/http` 封装而成,如有更多需求可以联系作者。
```ts
function request(options: {
function fetch(options: {
url: string; //请求地址
method: string; //请求方法
headers: { [key: string]: string }; //请求头
+1 -1
View File
@@ -8,6 +8,6 @@
</head>
<body>
<div id="root"></div>
<script src="/admin/umi.d87f33ac.js"></script>
<script src="/admin/umi.4dec6745.js"></script>
</body></html>
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+142 -1
View File
@@ -3,6 +3,7 @@ package core
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
u "net/url"
"strconv"
@@ -14,7 +15,147 @@ import (
"github.com/goccy/go-json"
)
func request(vm *goja.Runtime, resolve func(result interface{}), reject func(reason interface{}), wts ...interface{}) {
func request(wt interface{}, handles ...func(error, map[string]interface{}, interface{}) interface{}) interface{} {
var method = "get"
var url = ""
var req *http.Request
var headers map[string]interface{}
// var formData map[string]interface{}
var isJson bool
var isJsonBody bool
var body string
var allow_redirects bool = true
// var useproxy bool
// var timeout time.Duration = 0
var goroutine = false
var uuid = ""
switch wt := wt.(type) {
case string:
url = wt
default:
props := wt.(map[string]interface{})
for i := range props {
switch strings.ToLower(i) {
// case "timeout":
// timeout = time.Duration(utils.Int64(props[i])) * time.Millisecond
case "headers":
headers = props[i].(map[string]interface{})
case "method":
method = strings.ToLower(props[i].(string))
case "url":
if f, ok := props[i].(func(i goja.FunctionCall) goja.Value); ok {
url = f(goja.FunctionCall{}).ToString().String()
} else {
url = props[i].(string)
}
case "json":
isJson = props[i].(bool)
case "uuid":
uuid = props[i].(string)
case "goroutine":
goroutine = true
case "datatype":
switch props[i].(type) {
case string:
switch strings.ToLower(props[i].(string)) {
case "json":
isJson = true
}
}
case "allowredirects":
allow_redirects = props[i].(bool)
case "body":
if v, ok := props[i].(string); !ok {
d, _ := json.Marshal(props[i])
body = string(d)
isJsonBody = true
} else {
body = v
}
// case "formdata":
// formData = props[i].(map[string]interface{})
// case "useproxy":
// useproxy = props[i].(bool)
}
}
}
method = strings.ToUpper(method)
req, _ = http.NewRequest(method, url, bytes.NewBuffer([]byte(body)))
// if timeout != 0 {
// req.SetTimeout(timeout, timeout)
// }
if isJsonBody {
req.Header.Set("Content-Type", "application/json")
}
for i := range headers {
req.Header.Set(i, fmt.Sprint(headers[i]))
}
// for i := range formData {
// req.Param(i, fmt.Sprint(formData[i]))
// }
// if useproxy && Transport != nil {
// req.SetTransport(Transport)
// }
rspObj := map[string]interface{}{}
var rsp *http.Response
var err error
// if !allow_redirects {
// req.SetCheckRedirect(func(req *http.Request, via []*http.Request) error {
// return http.ErrUseLastResponse
// })
// }
var dddd = func() interface{} {
client := &http.Client{}
if !allow_redirects {
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
}
rsp, err = client.Do(req)
var bd interface{}
if err == nil {
defer rsp.Body.Close()
rspObj["status"] = rsp.StatusCode
rspObj["statusCode"] = rsp.StatusCode
data, _ := ioutil.ReadAll(rsp.Body)
if isJson {
var v interface{}
json.Unmarshal(data, &v)
bd = v
} else {
bd = string(data)
}
rspObj["body"] = bd
h := make(map[string][]string)
for k := range rsp.Header {
h[k] = rsp.Header[k]
}
rspObj["headers"] = h
} else {
rspObj["error"] = err.Error()
}
if uuid != "" {
rspObj["uuid"] = uuid
}
if len(handles) > 0 {
return handles[0](err, rspObj, bd)
} else {
return rspObj
}
}
if goroutine {
go dddd()
} else {
return dddd()
}
return nil
}
func fetch(vm *goja.Runtime, resolve func(result interface{}), reject func(reason interface{}), wts ...interface{}) {
var method = "get"
var url = ""
var req *http.Request
+3 -2
View File
@@ -359,7 +359,7 @@ func SetPluginMethod(vm *goja.Runtime, uuid string, on_start bool) {
vm.Set("Buffer", func(call goja.ConstructorCall) *goja.Object {
return Buffer(vm, call)
})
vm.Set("request", func(wts ...interface{}) interface{} {
vm.Set("fetch", func(wts ...interface{}) interface{} {
promise, resolve, reject := vm.NewPromise()
func() {
func() {
@@ -373,10 +373,11 @@ func SetPluginMethod(vm *goja.Runtime, uuid string, on_start bool) {
}
}()
request(vm, resolve, reject, wts...)
fetch(vm, resolve, reject, wts...)
}()
return promise
})
vm.Set("request", request)
}
func EncryptPlugin(script string) string {
-36
View File
@@ -41,8 +41,6 @@ func Cors() gin.HandlerFunc {
var Server = gin.New()
func init() {
gin.SetMode(gin.ReleaseMode)
// Server.Use(gin.Recovery())
Server.Use(Cors())
Server.Use(gzip.Gzip(gzip.DefaultCompression))
Server.NoRoute(func(c *gin.Context) {
@@ -131,9 +129,6 @@ func init() {
}
c.String(404, "页面被喵咪劫走了。") //
//开启代理模式
// handleHTTP(c.Writer, c.Request)
})
port := sillyGirl.GetString("port", "8080")
@@ -189,37 +184,6 @@ func init() {
}()
}
// var httpProxys = MakeBucket("httpProxys")
func handleHTTP(w http.ResponseWriter, req *http.Request) {
// console.Info("%s", utils.JsonMarshal(req.Header))
// u, err := url.Parse("addr")
// if err != nil {
// core.Logs.Warn("can't connect to the http proxy:", err)
// return
// }
// Transport = &http.Transport{Proxy: http.ProxyURL(u)}
// resp, err := Transport.RoundTrip(req)
// fmt.Println("====")
resp, err := http.DefaultTransport.RoundTrip(req)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
defer resp.Body.Close()
copyHeader(w.Header(), resp.Header)
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}
func copyHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}
type Req struct {
Method string
Path string