├── config.json ├── main.go ├── README.md ├── .vscode └── launch.json ├── .gitignore ├── hlog └── logger.go ├── util.go ├── js_interpreter.go ├── lib └── sandbox.js ├── client.go ├── runner.go └── LICENSE /config.json: -------------------------------------------------------------------------------- 1 | { 2 | "Address": "localhost:11011", 3 | "Interval": 10 4 | } -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "runtime" 5 | 6 | "github.com/brookshi/Hitchhiker-Node/hlog" 7 | ) 8 | 9 | func main() { 10 | runtime.GOMAXPROCS(runtime.NumCPU()) 11 | hlog.Info.Println("set max procs: ", runtime.NumCPU()) 12 | client := &client{} 13 | client.Do() 14 | } 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hitchhiker-Node 2 | 3 | Stress Test Node for [Hitchhiker](https://github.com/brookshi/Hitchhiker). 4 | 5 | ## How to use 6 | 7 | Download the zip file in release page, unzip, open config.json file and change value of `Address` to the Hitchhiker server's ip, eg: (192.168.0.2:11010). 8 | Then run it. -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [{ 4 | "name": "Launch Package", 5 | "type": "go", 6 | "request": "launch", 7 | "mode": "debug", 8 | "program": "${workspaceRoot}", 9 | "showLog": true, 10 | "env": {} 11 | }] 12 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 6 | *.log 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 15 | .glide/ 16 | 17 | debug 18 | Hitchhiker-Node* 19 | release/ 20 | global_data/ 21 | global_data.zip -------------------------------------------------------------------------------- /hlog/logger.go: -------------------------------------------------------------------------------- 1 | package hlog 2 | 3 | import ( 4 | "io" 5 | "log" 6 | "os" 7 | ) 8 | 9 | var ( 10 | Info *log.Logger 11 | Warn *log.Logger 12 | Error *log.Logger 13 | ) 14 | 15 | func init() { 16 | file, err := os.OpenFile("client.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) 17 | if err != nil { 18 | log.Fatalln("open log file failed: ", err) 19 | } 20 | 21 | Info = log.New(io.MultiWriter(os.Stdout, file), "info: ", log.Ldate|log.Ltime|log.Lshortfile) 22 | Warn = log.New(io.MultiWriter(os.Stdout, file), "warn: ", log.Ldate|log.Ltime|log.Lshortfile) 23 | Error = log.New(io.MultiWriter(os.Stderr, file), "error: ", log.Ldate|log.Ltime|log.Lshortfile) 24 | } 25 | -------------------------------------------------------------------------------- /util.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "archive/zip" 5 | "encoding/json" 6 | "io" 7 | "io/ioutil" 8 | "log" 9 | "os" 10 | "path/filepath" 11 | "strings" 12 | 13 | "github.com/brookshi/Hitchhiker-Node/hlog" 14 | ) 15 | 16 | func readConfig() (config, error) { 17 | var c config 18 | file, err := ioutil.ReadFile("./config.json") 19 | if err != nil { 20 | hlog.Error.Println("read config failed: ", err) 21 | return c, err 22 | } 23 | err = json.Unmarshal(file, &c) 24 | return c, err 25 | } 26 | 27 | func saveFile(data []byte) error { 28 | if _, err := os.Stat(dataFilePath); !os.IsNotExist(err) { 29 | os.Remove(dataFilePath) 30 | } 31 | 32 | f, err := os.OpenFile(dataFilePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) 33 | if err != nil { 34 | return err 35 | } 36 | n, err := f.Write(data) 37 | if err == nil && n < len(data) { 38 | err = io.ErrShortWrite 39 | } 40 | if err1 := f.Close(); err == nil { 41 | err = err1 42 | } 43 | return err 44 | } 45 | 46 | func unzip(src, dest string) ([]string, error) { 47 | var filenames []string 48 | r, err := zip.OpenReader(src) 49 | if err != nil { 50 | return filenames, err 51 | } 52 | 53 | defer r.Close() 54 | 55 | for _, f := range r.File { 56 | rc, err := f.Open() 57 | if err != nil { 58 | return filenames, err 59 | } 60 | defer rc.Close() 61 | fpath := filepath.Join(dest, f.Name) 62 | filenames = append(filenames, fpath) 63 | 64 | if f.FileInfo().IsDir() { 65 | os.MkdirAll(fpath, os.ModePerm) 66 | } else { 67 | var fdir string 68 | if lastIndex := strings.LastIndex(fpath, string(os.PathSeparator)); lastIndex > -1 { 69 | fdir = fpath[:lastIndex] 70 | } 71 | 72 | err = os.MkdirAll(fdir, os.ModePerm) 73 | if err != nil { 74 | log.Fatal(err) 75 | return filenames, err 76 | } 77 | f, err := os.OpenFile( 78 | fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) 79 | if err != nil { 80 | return filenames, err 81 | } 82 | defer f.Close() 83 | 84 | _, err = io.Copy(f, rc) 85 | if err != nil { 86 | return filenames, err 87 | } 88 | } 89 | } 90 | return filenames, nil 91 | } 92 | -------------------------------------------------------------------------------- /js_interpreter.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "time" 7 | 8 | "fknsrs.biz/p/ottoext/loop" 9 | "github.com/brookshi/Hitchhiker-Node/hlog" 10 | 11 | "github.com/robertkrimen/otto" 12 | // duktape "gopkg.in/olebedev/go-duktape.v2" 13 | ) 14 | 15 | type testResult struct { 16 | Tests map[string]bool `json:"tests"` 17 | Variables map[string]string `json:"variables"` 18 | } 19 | 20 | const ( 21 | Duktape = iota 22 | Otto 23 | ) 24 | 25 | const template = ` 26 | var responseObj = {}; 27 | try { 28 | responseObj = JSON.parse(responseBody); 29 | } catch (e) { 30 | responseObj = e; 31 | } 32 | var responseCode = { code: responseCode_Status, name: responseCode_Msg }; 33 | var responseHeaders = {}; 34 | try { 35 | responseHeaders = JSON.parse(responseHeaders_Str); 36 | } catch (e) { 37 | responseHeaders = e; 38 | } 39 | 40 | var $variables$ = {}; 41 | var tests = {}; 42 | var $variables$ = {}; 43 | var $export$ = function(obj){ }; 44 | %s 45 | $$out = JSON.stringify({tests: tests, variables: $variables$}); 46 | ` 47 | 48 | func interpret(engine byte, jsStr string, runResult runResult) testResult { 49 | if engine == Otto { 50 | return ottoInterpret(jsStr, runResult) 51 | } 52 | 53 | return duktapeInterpret(jsStr, runResult) 54 | } 55 | 56 | func ottoInterpret(jsStr string, runResult runResult) (result testResult) { 57 | vm := otto.New() 58 | l := loop.New(vm) 59 | vm.Set("responseBody", runResult.Body) 60 | vm.Set("responseCode_Status", runResult.Status) 61 | vm.Set("responseCode_Msg", runResult.StatusMessage) 62 | headers, _ := json.Marshal(runResult.Headers) 63 | vm.Set("responseHeaders_Str", string(headers)) 64 | vm.Set("responseTime", float64((runResult.Duration.Connect+runResult.Duration.DNS+runResult.Duration.Request).Nanoseconds())/float64(time.Millisecond)) 65 | err := l.EvalAndRun(fmt.Sprintf(template, jsStr)) 66 | testRst, err := vm.Get("$$out") 67 | result = testResult{ 68 | Tests: make(map[string]bool), 69 | Variables: make(map[string]string), 70 | } 71 | if err != nil { 72 | result.Tests[err.Error()] = false 73 | } else { 74 | json.Unmarshal([]byte(testRst.String()), &result) 75 | } 76 | for k, v := range result.Tests { 77 | hlog.Info.Println(k, v) 78 | } 79 | for k, v := range result.Variables { 80 | hlog.Info.Println(k, v) 81 | } 82 | return 83 | } 84 | 85 | func duktapeInterpret(jsStr string, runResult runResult) (result testResult) { 86 | // ctx := duktape.New() 87 | // ctx.PushString(runResult.Body) 88 | // ctx.PutGlobalString("responseBody") 89 | // ctx.PushNumber(float64((runResult.Duration.Connect + runResult.Duration.DNS + runResult.Duration.Request).Nanoseconds()) / float64(time.Millisecond)) 90 | // ctx.PutGlobalString("responseTime") 91 | // ctx.PushNumber(float64(runResult.Status)) 92 | // ctx.PutGlobalString("responseCode_Status") 93 | // ctx.PushString(runResult.StatusMessage) 94 | // ctx.PutGlobalString("responseCode_Msg") 95 | // headers, _ := json.Marshal(runResult.Headers) 96 | // ctx.PushString(string(headers)) 97 | // ctx.PutGlobalString("responseHeaders_Str") 98 | 99 | // err := ctx.PevalString(fmt.Sprintf(template, jsStr)) 100 | // data := ctx.GetString(-1) 101 | // if err != nil { 102 | // result.Tests[err.Error()] = false 103 | // } else { 104 | // json.Unmarshal([]byte(data), &result) 105 | // } 106 | return 107 | } 108 | -------------------------------------------------------------------------------- /lib/sandbox.js: -------------------------------------------------------------------------------- 1 | var SandboxRequest = (function () { 2 | function SandboxRequest() {} 3 | return SandboxRequest; 4 | }()); 5 | var Sandbox = (function () { 6 | function Sandbox(projectId, vid, envId, envName, variables, allProjectJsFiles, dataFiles, record) { 7 | var _this = this; 8 | this.projectId = projectId; 9 | this.vid = vid; 10 | this.envId = envId; 11 | this.envName = envName; 12 | this._allProjectJsFiles = {}; 13 | this._projectDataFiles = {}; 14 | this.tests = {}; 15 | this.exportObj = { 16 | content: Sandbox.defaultExport 17 | }; 18 | this.variables = variables; 19 | this._allProjectJsFiles = allProjectJsFiles; 20 | this._projectDataFiles = dataFiles; 21 | if (record) { 22 | this.request = { 23 | url: record.url, 24 | method: record.method || 'GET', 25 | body: record.body, 26 | headers: {} 27 | }; 28 | record.headers.filter(function (h) { 29 | return h.isActive; 30 | }).forEach(function (h) { 31 | _this.request.headers[h.key] = h.value; 32 | }); 33 | } 34 | } 35 | Sandbox.prototype.getProjectFile = function (file, type) { 36 | return "./global_data/" + this.projectId + "/" + type + "/" + file; 37 | }; 38 | Sandbox.prototype.require = function (lib) { 39 | if (!this._allProjectJsFiles[lib]) { 40 | throw new Error("no valid js lib named [" + lib + "], you should upload this lib first."); 41 | } 42 | var libPath = this._allProjectJsFiles[lib]; 43 | if (!libPath) { 44 | throw new Error("[" + libPath + "] does not exist."); 45 | } 46 | return require(libPath); 47 | }; 48 | Sandbox.prototype.readFile = function (file) { 49 | return ""; //this.readFileByReader(file, f => fs.readFileSync(f, 'utf8')); 50 | }; 51 | Sandbox.prototype.readFileByReader = function (file, reader) { 52 | if (this._projectDataFiles[file]) { 53 | return reader(this._projectDataFiles[file]); 54 | } 55 | throw new Error(file + " not exists."); 56 | }; 57 | Sandbox.prototype.saveFile = function (file, content, replaceIfExist) { 58 | if (replaceIfExist === void 0) { 59 | replaceIfExist = true; 60 | } 61 | //ProjectDataService.instance.saveDataFile(this.projectId, file, content, replaceIfExist); 62 | }; 63 | Sandbox.prototype.removeFile = function (file) { 64 | //ProjectDataService.instance.removeFile(ProjectDataService.dataFolderName, this.projectId, file); 65 | }; 66 | Sandbox.prototype.setEnvVariable = function (key, value) { 67 | this.variables[key] = value; 68 | }; 69 | Sandbox.prototype.getEnvVariable = function (key) { 70 | return this.variables[key]; 71 | }; 72 | Sandbox.prototype.removeEnvVariable = function (key) { 73 | Reflect.deleteProperty(this.variables, key); 74 | }; 75 | Sandbox.prototype.setRequest = function (r) { 76 | this.request = r; 77 | }; 78 | Object.defineProperty(Sandbox.prototype, "environment", { 79 | get: function () { 80 | return this.envName; 81 | }, 82 | enumerable: true, 83 | configurable: true 84 | }); 85 | Sandbox.prototype.export = function (obj) { 86 | this.exportObj.content = obj; 87 | };; 88 | return Sandbox; 89 | }()); 90 | Sandbox.defaultExport = 'export:impossiblethis:tropxe'; 91 | //# sourceMappingURL=sandbox_stress.js.map -------------------------------------------------------------------------------- /client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "os" 6 | "runtime" 7 | "time" 8 | 9 | "github.com/brookshi/Hitchhiker-Node/hlog" 10 | "golang.org/x/net/websocket" 11 | ) 12 | 13 | const ( 14 | msgHardware = iota 15 | msgTask 16 | msgStart 17 | msgRunResult 18 | msgStop 19 | msgStatus 20 | msgFileStart 21 | msgFileFinish 22 | ) 23 | 24 | const ( 25 | statusIdle = iota 26 | statusReady 27 | statusWorking 28 | statusFinish 29 | statusDown 30 | statusFileReady 31 | ) 32 | 33 | const dataFilePath = "./global_data.zip" 34 | 35 | type config struct { 36 | Address string 37 | Interval time.Duration 38 | } 39 | 40 | type client struct { 41 | conn *websocket.Conn 42 | errChan chan bool 43 | testCase testCase 44 | isFile bool 45 | } 46 | 47 | type message struct { 48 | Status byte `json:"status"` 49 | Type byte `json:"type"` 50 | TestCase testCase `json:"testCase"` 51 | RunResult runResult `json:"runResult"` 52 | CPUNum int `json:"cpuNum"` 53 | } 54 | 55 | func (c *client) Do() { 56 | hlog.Info.Println("read config") 57 | config, err := readConfig() 58 | if err != nil { 59 | hlog.Error.Println("read config file:", err) 60 | os.Exit(1) 61 | } 62 | 63 | for { 64 | c.errChan = make(chan bool) 65 | throttle := time.Tick(config.Interval * time.Second) 66 | c.conn, err = websocket.Dial("ws://"+config.Address, "", "http://"+config.Address) 67 | if err != nil { 68 | hlog.Error.Println("connect:", err) 69 | go func() { c.errChan <- true }() 70 | } else { 71 | hlog.Info.Println("connect: success") 72 | c.send(message{Status: statusIdle, Type: msgHardware, RunResult: runResult{ID: "1"}, CPUNum: runtime.NumCPU()}) 73 | hlog.Info.Println("status: idle") 74 | go c.read() 75 | } 76 | <-c.errChan 77 | <-throttle 78 | hlog.Info.Println("retry") 79 | } 80 | } 81 | 82 | func (c *client) read() { 83 | defer c.conn.Close() 84 | for { 85 | if c.isFile { 86 | c.receiveFile() 87 | } else { 88 | c.receiveJSON() 89 | } 90 | } 91 | } 92 | 93 | func (c *client) receiveFile() { 94 | var data []byte 95 | err := websocket.Message.Receive(c.conn, &data) 96 | if err != nil { 97 | c.readErr(err) 98 | return 99 | } 100 | if len(data) == 3 && data[0] == 36 { 101 | c.isFile = false 102 | unzip(dataFilePath, "global_data/") 103 | go c.handleMsg(message{Type: msgFileFinish}) 104 | } else { 105 | err = saveFile(data) 106 | if err != nil { 107 | c.readErr(err) 108 | return 109 | } 110 | } 111 | } 112 | 113 | func (c *client) receiveJSON() { 114 | var msg message 115 | err := websocket.JSON.Receive(c.conn, &msg) 116 | if err != nil { 117 | c.readErr(err) 118 | return 119 | } 120 | buf, _ := json.Marshal(msg) 121 | hlog.Info.Println("read: ", string(buf)) 122 | if msg.Type == msgFileStart { 123 | hlog.Info.Println("status: file start") 124 | c.isFile = true 125 | } 126 | go c.handleMsg(msg) 127 | } 128 | 129 | func (c *client) readErr(e error) { 130 | hlog.Error.Println("read:", e) 131 | c.testCase.stop() 132 | c.errChan <- true 133 | } 134 | 135 | func (c *client) handleMsg(msg message) { 136 | switch msg.Type { 137 | case msgTask: 138 | c.testCase = msg.TestCase 139 | c.testCase.trace = func(rst runResult) { 140 | hlog.Info.Println("trace") 141 | c.send(message{Status: statusWorking, Type: msgRunResult, RunResult: rst}) 142 | } 143 | c.send(message{Status: statusReady, Type: msgStatus}) 144 | hlog.Info.Println("status: ready") 145 | case msgStart: 146 | hlog.Info.Println("status: start") 147 | c.send(message{Status: statusWorking, Type: msgStatus}) 148 | c.testCase.Run() 149 | c.finish() 150 | case msgFileFinish: 151 | hlog.Info.Println("status: file finish") 152 | c.send(message{Status: statusFileReady, Type: msgStatus}) 153 | case msgStop: 154 | c.finish() 155 | } 156 | } 157 | 158 | func (c *client) send(msg message) { 159 | buf, err := json.Marshal(msg) 160 | if err != nil { 161 | hlog.Error.Println("stringify message error: ", err) 162 | return 163 | } 164 | hlog.Info.Println("send request run result", msg.Type) 165 | c.conn.Write(buf) 166 | } 167 | 168 | func (c *client) finish() { 169 | c.testCase.stop() 170 | c.send(message{Status: statusFinish, Type: msgStatus}) 171 | } 172 | -------------------------------------------------------------------------------- /runner.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "io/ioutil" 7 | "net/http" 8 | "net/http/httptrace" 9 | "net/url" 10 | "strings" 11 | "sync" 12 | "sync/atomic" 13 | "time" 14 | ) 15 | 16 | type testCase struct { 17 | RequestBodyList []requestBody `json:"requestBodyList"` 18 | EnvVariables map[string]string `json:"envVariables"` 19 | Repeat int `json:"repeat"` 20 | ConcurrencyCount int `json:"concurrencyCount"` 21 | QPS int `json:"qps"` 22 | Timeout int `json:"timeout"` 23 | KeepAlive bool `json:"keepAlive"` 24 | results chan []runResult 25 | forceStop int32 26 | trace func(rst runResult) 27 | } 28 | 29 | type requestBody struct { 30 | ID string `json:"id"` 31 | Param string `json:"param"` 32 | Method string `json:"method"` 33 | URL string `json:"url"` 34 | Body string `json:"body"` 35 | Headers map[string]string `json:"headers"` 36 | Tests string `json:"test"` 37 | } 38 | 39 | type runResult struct { 40 | ID string `json:"id"` 41 | Success bool `json:"success"` 42 | Param string `json:"param"` 43 | Err runError `json:"error"` 44 | Body string `json:"body"` 45 | Status int `json:"status"` 46 | StatusMessage string `json:"statusMessage"` 47 | Duration duration `json:"duration"` 48 | Headers map[string]string `json:"headers"` 49 | Tests map[string]bool `json:"tests"` 50 | } 51 | 52 | type duration struct { 53 | DNS time.Duration `json:"dns"` 54 | Connect time.Duration `json:"connect"` 55 | Request time.Duration `json:"request"` 56 | } 57 | 58 | type runError struct { 59 | Message string `json:"message"` 60 | } 61 | 62 | func (c *testCase) Run() { 63 | c.results = make(chan []runResult, c.Repeat*c.ConcurrencyCount) 64 | atomic.StoreInt32(&c.forceStop, 0) 65 | c.start() 66 | close(c.results) 67 | } 68 | 69 | func (c *testCase) start() { 70 | var waiter sync.WaitGroup 71 | waiter.Add(c.ConcurrencyCount) 72 | 73 | for i := 0; i < c.ConcurrencyCount; i++ { 74 | go func() { 75 | c.work(c.Repeat) 76 | waiter.Done() 77 | }() 78 | } 79 | waiter.Wait() 80 | } 81 | 82 | func (c *testCase) work(times int) { 83 | var throttle <-chan time.Time 84 | if c.QPS > 0 { 85 | throttle = time.Tick(time.Duration(1e6/(c.QPS)) * time.Microsecond) 86 | } 87 | 88 | transport := &http.Transport{ 89 | DisableKeepAlives: !c.KeepAlive, 90 | } 91 | httpClient := http.Client{Transport: transport, Timeout: time.Duration(c.Timeout) * time.Second} 92 | for i := 0; i < times; i++ { 93 | if c.QPS > 0 { 94 | <-throttle 95 | } 96 | if atomic.CompareAndSwapInt32(&c.forceStop, 1, 1) { 97 | break 98 | } 99 | c.doRequest(httpClient) 100 | } 101 | } 102 | 103 | func (c *testCase) doRequest(httpClient http.Client) { 104 | results := make([]runResult, len(c.RequestBodyList)) 105 | variables := make(map[string]string) 106 | cookies := make(map[string]string) 107 | for i, body := range c.RequestBodyList { 108 | results[i] = doRequestItem(body, httpClient, c.EnvVariables, variables, cookies) 109 | if c.trace != nil { 110 | c.trace(results[i]) 111 | } 112 | } 113 | c.results <- results 114 | } 115 | 116 | func (c *testCase) stop() { 117 | atomic.CompareAndSwapInt32(&c.forceStop, 0, 1) 118 | } 119 | 120 | func doRequestItem(body requestBody, httpClient http.Client, envVariables map[string]string, variables map[string]string, cookies map[string]string) (result runResult) { 121 | var dnsStart, connectStart, reqStart time.Time 122 | var duration duration 123 | result = runResult{ID: body.ID, Param: body.Param, Success: false} 124 | 125 | //now := time.Now() 126 | req, err := buildRequest(body, cookies, envVariables, variables) 127 | 128 | if err != nil { 129 | fmt.Println(err) 130 | result.Err = runError{err.Error()} 131 | if req != nil { 132 | req.Close = true 133 | } 134 | } else { 135 | trace := &httptrace.ClientTrace{ 136 | DNSStart: func(info httptrace.DNSStartInfo) { 137 | dnsStart = time.Now() 138 | }, 139 | DNSDone: func(info httptrace.DNSDoneInfo) { 140 | duration.DNS = time.Now().Sub(dnsStart) 141 | }, 142 | GetConn: func(hostPort string) { 143 | connectStart = time.Now() 144 | }, 145 | GotConn: func(info httptrace.GotConnInfo) { 146 | duration.Connect = time.Now().Sub(connectStart) 147 | }, 148 | WroteRequest: func(info httptrace.WroteRequestInfo) { 149 | reqStart = time.Now() 150 | }, 151 | GotFirstResponseByte: func() { 152 | duration.Request = time.Now().Sub(reqStart) 153 | }, 154 | } 155 | req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace)) 156 | res, err := httpClient.Do(req) 157 | if err == nil { 158 | result.Duration = duration 159 | result.Status = res.StatusCode 160 | result.StatusMessage = parseStatusMsg(res.Status, res.StatusCode) 161 | result.Headers = make(map[string]string) 162 | for k, v := range res.Header { 163 | hv := strings.Join(v, ";") 164 | result.Headers[k] = hv 165 | if strings.ToLower(k) == "cookie" { 166 | for sk, sv := range readCookies(hv) { 167 | cookies[sk] = sv 168 | } 169 | } 170 | } 171 | content, err := ioutil.ReadAll(res.Body) 172 | if err != nil { 173 | result.Err = runError{err.Error()} 174 | } else { 175 | result.Body = string(content) 176 | } 177 | 178 | testsStr := prepareTests(body.Tests, variables, envVariables) 179 | testResult := interpret(Otto, testsStr, result) 180 | result.Tests = make(map[string]bool) 181 | for k, v := range testResult.Tests { 182 | result.Tests[k] = v 183 | } 184 | for k, v := range testResult.Variables { 185 | variables[k] = v 186 | } 187 | result.Success = true 188 | defer res.Body.Close() 189 | } else { 190 | result.Err = runError{err.Error()} 191 | } 192 | } 193 | return 194 | } 195 | 196 | func buildRequest(reqBody requestBody, cookies map[string]string, envVariables map[string]string, variables map[string]string) (*http.Request, error) { 197 | var bodyReader io.Reader 198 | if reqBody.Body != "" { 199 | bodyReader = strings.NewReader(applyAllVariables(reqBody.Body, variables, envVariables)) 200 | } 201 | req, err := http.NewRequest(reqBody.Method, encodeUrl(applyAllVariables(reqBody.URL, variables, envVariables)), bodyReader) 202 | if err != nil { 203 | return nil, err 204 | } 205 | headers := make(http.Header) 206 | for k, v := range reqBody.Headers { 207 | if strings.ToLower(k) == "cookie" { 208 | v = applyCookies(v, cookies) 209 | } 210 | headers.Set(applyAllVariables(k, variables, envVariables), applyAllVariables(v, variables, envVariables)) 211 | } 212 | req.Header = headers 213 | return req, nil 214 | } 215 | 216 | func applyAllVariables(content string, variables map[string]string, envVariables map[string]string) string { 217 | return applyVariables(applyVariables(content, variables), envVariables) 218 | } 219 | 220 | func applyVariables(content string, variables map[string]string) string { 221 | if len(content) == 0 || len(variables) == 0 { 222 | return content 223 | } 224 | for k, v := range variables { 225 | content = strings.Replace(content, fmt.Sprintf("{{%s}}", k), v, -1) 226 | } 227 | return content 228 | } 229 | 230 | func applyCookies(value string, cookies map[string]string) string { 231 | if len(cookies) == 0 || value == "nocookie" { 232 | return value 233 | } 234 | 235 | recordCookies := readCookies(value) 236 | for k, v := range cookies { 237 | if _, ok := recordCookies[k]; !ok { 238 | value = fmt.Sprintf("%s;%s", value, v) 239 | } 240 | } 241 | return value 242 | } 243 | 244 | func readCookies(cookies string) map[string]string { 245 | cookieMap := make(map[string]string) 246 | cookieArr := strings.Split(cookies, ";") 247 | for _, v := range cookieArr { 248 | v = strings.Trim(v, " ") 249 | i := strings.Index(v, "=") 250 | if i < 0 { 251 | i = len(v) 252 | } 253 | cookieMap[v[:i]] = v 254 | } 255 | return cookieMap 256 | } 257 | 258 | func prepareTests(tests string, variables map[string]string, envVariables map[string]string) string { 259 | return applyAllVariables(tests, variables, envVariables) 260 | } 261 | 262 | func parseStatusMsg(status string, statusCode int) string { 263 | statusCodeStr := string(statusCode) 264 | if strings.HasPrefix(status, statusCodeStr) { 265 | status = strings.Trim(strings.TrimPrefix(status, statusCodeStr), " ") 266 | } 267 | return status 268 | } 269 | 270 | func encodeUrl(u string) string { 271 | var Url *url.URL 272 | Url, err := url.Parse(u) 273 | if err != nil { 274 | return u 275 | } 276 | 277 | queryStrings := Url.Query() 278 | Url.RawQuery = queryStrings.Encode() 279 | return Url.String() 280 | } 281 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | --------------------------------------------------------------------------------