From 205c4f20dc91e78ee94c99a81b5cc136c5ca9656 Mon Sep 17 00:00:00 2001 From: Star Date: Thu, 3 Oct 2024 12:24:08 +0800 Subject: [PATCH] add file.readBytes change http result to r.bytes(), r.string(), r.object() --- modules/file/file.go | 10 +++++++++- modules/http/http.go | 33 +++++++++++++++++++++++++++++++-- modules/http/http.ts | 5 +++-- 3 files changed, 43 insertions(+), 5 deletions(-) diff --git a/modules/file/file.go b/modules/file/file.go index 472a05e..50844c9 100644 --- a/modules/file/file.go +++ b/modules/file/file.go @@ -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)) diff --git a/modules/http/http.go b/modules/http/http.go index 5515a23..6306fcb 100644 --- a/modules/http/http.go +++ b/modules/http/http.go @@ -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) diff --git a/modules/http/http.ts b/modules/http/http.ts index 60a5421..c42dab6 100644 --- a/modules/http/http.ts +++ b/modules/http/http.ts @@ -40,6 +40,7 @@ interface Result { status: string statusCode: number headers: Object - data: Object - result: string + bytes(): Uint8Array + string(): string + object(): Object }