我想将操作系统命令的退出代码传递给 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/