entr go run not playing nice

问题描述 投票:0回答:3

我正在

go
中进行一些轻量级 Web 开发,并遇到了
entr
的问题。我正在编辑目录中的
.go
文件,同时具有

ls *.go | entr -r go run *.go

在单独的终端窗口中运行。

我每次保存文件时都可以看到它重新启动我的程序,因为每次我这样做时都会将一些格式语句打印到终端。但是,每当我导航到

localhost:8080
时,我都会看到启动
entr
时存在的处理程序内容(而不是最近更改中的内容)。如果我
Ctrl+C
,那么重启
entr
,我看到最新的变化了

知道我做错了什么吗?

这是最小的例子:

// test.go
package main

import (
    "fmt"
    "net/http"
)

func handler (w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello there! I love %s!", r.URL.Path[1:])
}

func main() {
    fmt.Println("Starting up...")
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

现在,如果我运行

ls test.go | entr -r go run test.go
,我会看到
Starting up...
打印到终端,然后我可以去
localhost:8080/tests
看到一个写着
"Hello there! I love tests!"
的页面。如果我更改
handler
函数,使其显示为

func handler (w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "I guess %s are ok...", r.URL.Path[1:])
}

我再次看到

Starting up...
消息打印在终端中,但是转到
localhost:8080/tests
仍然给我显示
"Hello there! I love tests!"
的页面(即使在隐身模式下)。如果我然后杀死
entr
进程并重新启动它,我可以去
localhost:8080/tests
看到预期的
I guess tests are ok...

编辑

ListenAndServe
中获取错误确认这与悬挂套接字有关。

...
   err := http.ListenAndServe(":8080", nil)
   fmt.Printf("ListenAndServe ERR: %s\n", err)
...

显示额外的行

listen tcp :8080: bind: address already in use

在终端。快速搜索告诉我,没有一种简单的方法可以阻止以

ListenAndServe
开头的侦听器。有没有比this更简单的方法?

go webserver restart
3个回答
1
投票

问题:

go run
将在一个不会被杀死的单独进程中启动服务器。

解决方案: 使用一个小脚本来终止并启动服务器

#!/bin/sh
pkill "$1"
go run "$1.go"

并将其用于

entr
.


1
投票

ls命令只列出你当前目录下的go文件。该命令应该是这样的来监听项目中所有子文件夹中的go文件。

find . | grep '\.go' | entr -r go run .

0
投票

在 linux 中创建了两个进程。第一个是 go run main.go,第二个是 /tmp/go-build/b001/exe/main。需要杀死第二个才能终止程序而不是第一个...

© www.soinside.com 2019 - 2024. All rights reserved.