json output

This commit is contained in:
Roman Volosovskyi 2016-06-23 16:56:02 +03:00
parent 6f02c4cc3c
commit 85abe12364
1 changed files with 15 additions and 11 deletions

View File

@ -3,6 +3,7 @@ package main
import ( import (
"github.com/robertkrimen/otto" "github.com/robertkrimen/otto"
"fmt" "fmt"
"encoding/json"
) )
var statusJs string var statusJs string
@ -12,18 +13,23 @@ func Init(js string) {
statusJs = js statusJs = js
} }
func printError(error string) string {
str := JSONError{
Error: error,
}
outBytes, _ := json.Marshal(&str)
return string(outBytes)
}
func printResult(res string, err error) string { func printResult(res string, err error) string {
var out string var out string
if err != nil { if err != nil {
out = fmt.Sprintf(`{ out = printError(err.Error())
"error": %s
}`,
err.Error())
} else { } else {
out = fmt.Sprintf(`{ if "undefined" == res {
"result": %s res = "null";
}`, }
res) out = fmt.Sprintf(`{"result": %s}`, res)
} }
return out return out
@ -44,9 +50,7 @@ func Parse(chatId string, js string) string {
func Call(chatId string, path string, args string) string { func Call(chatId string, path string, args string) string {
vm, ok := vms[chatId] vm, ok := vms[chatId]
if !ok { if !ok {
return fmt.Sprintf( return printError(fmt.Sprintf("Vm[%s] doesn't exist.", chatId))
"{\"error\":\"Vm[%s] doesn't exist.\"}",
chatId)
} }
res, err := vm.Call("call", nil, path, args) res, err := vm.Call("call", nil, path, args)