Created
June 7, 2018 08:43
-
-
Save shershen08/5e17acb91c241e0b14a98d56b679e353 to your computer and use it in GitHub Desktop.
gin server concept to execute bash commands
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 ( | |
"encoding/json" | |
"net/http" | |
"os/exec" | |
log "github.com/Sirupsen/logrus" | |
"github.com/gin-gonic/gin" | |
) | |
type Comand struct { | |
Text string `json:"text"` | |
Flags string `json:"flags,omitempty"` | |
} | |
func status(c *gin.Context) { | |
c.JSON(200, gin.H{ | |
"message": "pong", | |
}) | |
} | |
func execCmd(comand string) []byte { | |
cmdStr := comand | |
cmd := exec.Command("/bin/sh", "-c", cmdStr) | |
result, err := cmd.Output() | |
if err != nil { | |
log.Error(err.Error()) | |
return []byte("") | |
} | |
return result | |
} | |
func comand(c *gin.Context) { | |
var cmd Comand | |
decoder := json.NewDecoder(c.Request.Body) | |
errDecode := decoder.Decode(&cmd) | |
if errDecode != nil { | |
log.Error(errDecode) | |
c.String(http.StatusBadRequest, "Bad JSON encoding") | |
return | |
} | |
result := execCmd(cmd.Text) | |
//n := bytes.IndexByte(result, 0) | |
resultString := string(result[:]) | |
log.Info(cmd, resultString) | |
c.JSON(200, gin.H{"status": "success", "result": resultString}) | |
} | |
func main() { | |
r := gin.Default() | |
r.GET("/ping", status) | |
r.POST("/exec", comand) | |
r.Run() // listen and serve on 0.0.0.0:8080 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment