Last active
July 18, 2017 01:03
-
-
Save inokappa/ab5f871d209cd556b3a1fdcfe5a62286 to your computer and use it in GitHub Desktop.
コマンドの実行結果を JSON で返す郷
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"os/exec" | |
"time" | |
"flag" | |
"encoding/json" | |
"strings" | |
) | |
var ( | |
argCommand = flag.String("command", "", "Specify a Command.") | |
argTimes = flag.Int("times", 1, "Specify a Loop Counts Number.") | |
argInterval = flag.Int("interval", 3, "Specify a Wait Interval Times.") | |
) | |
type OutputMessages struct { | |
Outputs []string `json:"outputs"` | |
} | |
func runCommand(command string) (output string){ | |
cmd := exec.Command("sh", "-c", command) | |
result, err := cmd.CombinedOutput() | |
output = strings.TrimRight(string(result), "\n") | |
if err != nil { | |
// fmt.Println(err) | |
errMessage := err.Error() + ": " + output | |
log.Printf(string(errMessage)) | |
return output | |
} | |
return output | |
} | |
func main() { | |
flag.Parse() | |
if *argCommand == "" { | |
fmt.Println("Please specify `-command` option.") | |
os.Exit(1) | |
} | |
var stdout string | |
var stdouts []string | |
for i := 1; i <= *argTimes; i++ { | |
stdout = runCommand(*argCommand) | |
time.Sleep(time.Duration(*argInterval) * time.Second) | |
stdouts = append(stdouts, stdout) | |
} | |
outputMessage := OutputMessages{Outputs: []string(stdouts)} | |
jsonBytes, err := json.Marshal(outputMessage) | |
if err != nil { | |
fmt.Println(err.Error()) | |
os.Exit(1) | |
} | |
fmt.Println(string(jsonBytes)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment