71 lines
1.3 KiB
Go
71 lines
1.3 KiB
Go
package httpx
|
|
|
|
import "github.com/d5/tengo/v2"
|
|
import "net/http"
|
|
import "bytes"
|
|
import tjson "github.com/d5/tengo/v2/stdlib/json"
|
|
|
|
var Module = map[string] tengo.Object {
|
|
"get": &tengo.BuiltinFunction{
|
|
Name: "get",
|
|
Value: func(
|
|
args ...tengo.Object,
|
|
) (tengo.Object, error){
|
|
if len(args) != 1 {
|
|
return nil, tengo.ErrWrongNumArguments
|
|
}
|
|
url, ok := tengo.ToString(args[0])
|
|
if !ok {
|
|
return nil, tengo.ErrInvalidArgumentType{
|
|
Name: "first",
|
|
Expected: "string",
|
|
Found: args[0].TypeName(),
|
|
}
|
|
}
|
|
resp, err := http.Get(url)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &Response{
|
|
Response: resp,
|
|
}, nil
|
|
},
|
|
},
|
|
"post_json": &tengo.BuiltinFunction{
|
|
Name: "post",
|
|
Value: func(
|
|
args ...tengo.Object,
|
|
) (tengo.Object, error){
|
|
if len(args) < 2 {
|
|
return nil, tengo.ErrWrongNumArguments
|
|
}
|
|
url, ok := tengo.ToString(args[0])
|
|
if !ok {
|
|
return nil, tengo.ErrInvalidArgumentType{
|
|
Name: "first",
|
|
Expected: "string",
|
|
Found: args[0].TypeName(),
|
|
}
|
|
}
|
|
|
|
var body bytes.Buffer
|
|
ret, err := tjson.Encode(args[1])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
body.Write(ret)
|
|
|
|
resp, err := http.Post(
|
|
url, "application/json",
|
|
&body,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &Response{
|
|
Response: resp,
|
|
}, nil
|
|
},
|
|
},
|
|
}
|
|
|