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))
}
},
"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 {
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
} else {
panic(vm.NewGoError(err))

View File

@ -6,6 +6,7 @@ import (
_ "embed"
"github.com/ssgo/httpclient"
"github.com/ssgo/u"
"reflect"
)
//go:embed http.ts
@ -63,11 +64,39 @@ func makeResult(r *httpclient.Result, vm *goja.Runtime) goja.Value {
"status": r.Response.Status,
"statusCode": r.Response.StatusCode,
"headers": headers,
"data": r.Map(),
"result": r.String(),
"_data": r.Bytes(),
"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 {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
return makeResult(hc.client.Get(args.Str(0), args.Map2StrArr(1)...), vm)

View File

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