gpt4 book ai didi

go - 每隔一分钟执行一次命令并通过 http 提供输出

转载 作者:行者123 更新时间:2023-12-03 02:23:31 25 4
gpt4 key购买 nike

我想每隔一分钟在 Bash shell 中运行一个命令,并通过 http 在 http://localhost:8080/feed 上提供输出

package main

import (
"fmt"
"os/exec"
)

func main() {
cmd := `<a piped command>`
out, err := exec.Command("bash", "-c", cmd).Output()
if err != nil {
fmt.Sprintf("Failed to execute command: %s", cmd)
}
fmt.Println(string(out))
}

更新:

package main

import (
"fmt"
"log"
"net/http"
"os/exec"
)

func handler(w http.ResponseWriter, r *http.Request) {
cmd := `<a piped command>`
out, err := exec.Command("bash", "-c", cmd).Output()
if err != nil {
fmt.Sprintf("Failed to execute command: %s", cmd)
}
fmt.Fprintf(w, string(out))
}

func main() {
http.HandleFunc("/feed", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}

通过上面的代码,每次http://localhost:8080/feed都会运行该命令被访问。如何让它缓存(?)命令的输出一分钟,然后仅在缓存时间到期后再次运行该命令?

最佳答案

如果输出不太大,可以将其保存在内存变量中。我采取的方法是在执行脚本时等待结果(使用互斥体):

package main

import (
"fmt"
"net/http"
"os/exec"
"sync"
"time"
)

var LoopDelay = 60*time.Second

type Output struct {
sync.Mutex
content string
}


func main() {

var output *Output = new(Output)

go updateResult(output)

http.HandleFunc("/feed", initHandle(output))
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Println("ERROR", err)
}
}

func initHandle(output *Output) func(http.ResponseWriter, *http.Request) {
return func(respw http.ResponseWriter, req *http.Request) {
output.Lock()
defer output.Unlock()
_, err := respw.Write([]byte(output.content))
if err != nil {
fmt.Println("ERROR: Unable to write response: ", err)
}
}
}

func updateResult(output *Output) {
var execFn = func() { /* Extracted so that 'defer' executes at the end of loop iteration */
output.Lock()
defer output.Unlock()
command := exec.Command("bash", "-c", "date | nl ")
output1, err := command.CombinedOutput()
if err != nil {
output.content = err.Error()
} else {
output.content = string(output1)
}

}
for {
execFn()
time.Sleep(LoopDelay)
}
}

执行

date; curl http://localhost:8080/feed

给出输出(多次调用):

 1  dimanche 13 octobre 2019, 09:41:40 (UTC+0200)
http-server-cmd-output> date; curl http://localhost:8080/feed

dimanche 13 octobre 2019, 09:42:05 (UTC+0200)
1 dimanche 13 octobre 2019, 09:41:40 (UTC+0200)

需要考虑的一些事情:
- 使用“日期|” nl' 作为带管道的命令示例
- 如果输出太大,写入文件
- 很可能只为内容更新保留互斥体是个好主意(在脚本执行期间无需等待) - 您可以尝试改进它
- Go 例程可能有变量( channel )来根据信号退出(例如:程序结束时)

编辑:变量移至主函数

关于go - 每隔一分钟执行一次命令并通过 http 提供输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58361020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com