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