-
-
Notifications
You must be signed in to change notification settings - Fork 118
/
example_packages_test.go
131 lines (104 loc) · 2.28 KB
/
example_packages_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package vm_test
import (
"log"
"github.com/mattn/anko/env"
_ "github.com/mattn/anko/packages"
"github.com/mattn/anko/vm"
)
func Example_vmSort() {
// _ "github.com/mattn/anko/packages"
e := env.NewEnv()
script := `
fmt = import("fmt")
sort = import("sort")
a = [5, 1.1, 3, "f", "2", "4.4"]
sortFuncs = make(sort.SortFuncsStruct)
sortFuncs.LenFunc = func() { return len(a) }
sortFuncs.LessFunc = func(i, j) { return a[i] < a[j] }
sortFuncs.SwapFunc = func(i, j) { temp = a[i]; a[i] = a[j]; a[j] = temp }
sort.Sort(sortFuncs)
fmt.Println(a)
`
_, err := vm.Execute(e, nil, script)
if err != nil {
log.Fatalf("execute error: %v\n", err)
}
// output:
// [f 1.1 2 3 4.4 5]
}
func Example_vmRegexp() {
// _ "github.com/mattn/anko/packages"
e := env.NewEnv()
script := `
fmt = import("fmt")
regexp = import("regexp")
re = regexp.MustCompile("^simple$")
result = re.MatchString("simple")
fmt.Println(result)
fmt.Println("")
re = regexp.MustCompile("simple")
result = re.FindString("This is a simple sentence")
fmt.Println(result)
fmt.Println("")
re = regexp.MustCompile(",")
result = re.Split("a,b,c", -1)
fmt.Println(result)
fmt.Println("")
re = regexp.MustCompile("foo")
result = re.ReplaceAllString("foo", "bar")
fmt.Println(result)
`
_, err := vm.Execute(e, nil, script)
if err != nil {
log.Fatalf("execute error: %v\n", err)
}
// output:
// true
//
// simple
//
// [a b c]
//
// bar
}
func Example_vmHttp() {
// _ "github.com/mattn/anko/packages"
e := env.NewEnv()
script := `
fmt = import("fmt")
io = import("io")
ioutil = import("io/ioutil")
net = import("net")
http = import("net/http")
time = import("time")
func handlerRoot(responseWriter, request) {
io.WriteString(responseWriter, "Hello World :)")
}
serveMux = http.NewServeMux()
serveMux.HandleFunc("/", handlerRoot)
listener, err = net.Listen("tcp", ":8080")
if err != nil {
fmt.Println(err)
return
}
go http.Serve(listener, serveMux)
client = http.DefaultClient
response, err = client.Get("http://localhost:8080/")
if err != nil {
fmt.Println(err)
return
}
body, err = ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println(err)
}
response.Body.Close()
fmt.Printf("%s\n", body)
`
_, err := vm.Execute(e, nil, script)
if err != nil {
log.Fatalf("execute error: %v\n", err)
}
// output:
// Hello World :)
}