add file.readBytes

change http result to r.bytes(), r.string(), r.object()
This commit is contained in:
Star 2024-10-03 12:24:08 +08:00
parent 04e4f771fb
commit 205c4f20dc
3 changed files with 43 additions and 5 deletions

View File

@ -21,9 +21,17 @@ func init() {
panic(vm.NewGoError(err)) panic(vm.NewGoError(err))
} }
}, },
"readBytes": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
if r, err := u.ReadFileBytes(args.Path(0)); err == nil {
return vm.ToValue(r)
} else {
panic(vm.NewGoError(err))
}
},
"write": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value { "write": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(2) args := gojs.MakeArgs(&argsIn, vm).Check(2)
if err := u.WriteFileBytes(args.Path(0), u.Bytes(args.Any(0))); err == nil { if err := u.WriteFileBytes(args.Path(0), args.Bytes(0)); err == nil {
return nil return nil
} else { } else {
panic(vm.NewGoError(err)) panic(vm.NewGoError(err))

View File

@ -6,6 +6,7 @@ import (
_ "embed" _ "embed"
"github.com/ssgo/httpclient" "github.com/ssgo/httpclient"
"github.com/ssgo/u" "github.com/ssgo/u"
"reflect"
) )
//go:embed http.ts //go:embed http.ts
@ -63,11 +64,39 @@ func makeResult(r *httpclient.Result, vm *goja.Runtime) goja.Value {
"status": r.Response.Status, "status": r.Response.Status,
"statusCode": r.Response.StatusCode, "statusCode": r.Response.StatusCode,
"headers": headers, "headers": headers,
"data": r.Map(), "_data": r.Bytes(),
"result": r.String(), "bytes": toBytes,
"string": toString,
"object": toObject,
}) })
} }
func toBytes(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
dataValue := argsIn.This.ToObject(vm).Get("_data")
if _, ok := dataValue.Export().([]byte); ok {
return dataValue
}
return nil
}
func toString(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
dataValue := argsIn.This.ToObject(vm).Get("_data")
if data, ok := dataValue.Export().([]byte); ok {
return vm.ToValue(string(data))
}
return nil
}
func toObject(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
dataValue := argsIn.This.ToObject(vm).Get("_data")
if data, ok := dataValue.Export().([]byte); ok {
obj := u.UnJsonBytes(data, nil)
v := u.FinalValue(reflect.ValueOf(obj))
return vm.ToValue(v.Interface())
}
return nil
}
func (hc *Http) Get(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value { func (hc *Http) Get(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1) args := gojs.MakeArgs(&argsIn, vm).Check(1)
return makeResult(hc.client.Get(args.Str(0), args.Map2StrArr(1)...), vm) return makeResult(hc.client.Get(args.Str(0), args.Map2StrArr(1)...), vm)

View File

@ -40,6 +40,7 @@ interface Result {
status: string status: string
statusCode: number statusCode: number
headers: Object headers: Object
data: Object bytes(): Uint8Array
result: string string(): string
object(): Object
} }