go - 如何将 os/exec 输出传递给 gin get

标签 go

我想将操作系统命令的退出代码传递给 URL。我正在使用 Gin ,但我对任何方式都持开放态度。

我只想将错误传递给 HTTP 响应。

到目前为止,我找不到将 os 输出放入 HTTP 响应示例的示例,所以我来到这里希望有人知道。

package main
import (
        "fmt"
        "github.com/gin-gonic/gin"
        "os/exec"
)
func Homepage(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "Hello World"
        }
}

func Powershell(c *gin.Context) {
    // Run this powershell program from Go.
    cmd := exec.Command("powershell","-file","C:\\temp\\test.ps1")
    // Wait for the Powershell program to exit.
    err := cmd.Run()
    //fmt.Println("Finished:", err)}


    c.JSON(200, gin.H{
      "Message": "This is the PowerShell exit code not the script exit code",
      "Finished:", err

}

func main() {
    fmt.Println("hello world")
    r := gin.Default()
    r.GET("/", Homepage)
    r.GET("/app", Powershell)
    r.Run()
}

到目前为止,我尝试的所有操作都只是在 get/app 上出错

最佳答案

如果添加适合您的命令的完整响应,您可以使用以下代码来完成:

func Powershell(c *gin.Context) {
    cmd := exec.Command("powershell","-file","C:\\temp\\test.ps1")

    stdout, err := cmd.Output()
    if err != nil {
        c.JSON(200, gin.H{
            "Message": "Error occurs",
            "Finished": err,
        })
    } else {
        c.JSON(200, gin.H{
            "Message": string(stdout),
            "Finished": nil,
        })
    }
}

但是如果你只想得到一个数字代码,你可以按照this answer .我无法在 Windows 中测试此解决方案,也无法保证它适用于您的情况。

关于go - 如何将 os/exec 输出传递给 gin get,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57125155/

相关文章:

multithreading - 即使例程在 Golang 中发生了 "keep main thread running",如何返回 "runtime error"?

go - 用于动态枚举访问的 Protobuf API

go - make(map) 和 map{} 之间的区别

concurrency - 为什么函数会提前返回?

tree - Golang 中的这段代码是惯用的吗?持久化树

go - Go 编译文件如何在不同的操作系统或 CPU 架构上工作?

go - 在 "go-getable"包中选择不同的可执行文件名称

google-app-engine - blobstore.ParseUpload 在开发服务器和部署中的行为不同

go - Go 中的 ODBC 返回空/空白记录

python - 转换python正则表达式