I'm doing some light web development in go
, and running into a problem with entr
. I'm editing .go
files in a directory while having
ls *.go | entr -r go run *.go
running in a separate terminal window.
I can see it re-starting my program every time I save a file, because some format statements get printed out to the terminal every time I do so. However, whenever I navigate to localhost:8080
, I see the handler content that was present when I started entr
(rather than the content in the most recent change). If I Ctrl+C
, then restart entr
, I see the latest changes.
Any idea what I'm doing wrong?
Here's the minimal example:
// 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)
}
Now, if I run ls test.go | entr -r go run test.go
, I see Starting up...
printed to the terminal, and I can go to localhost:8080/tests
to see a page that says "Hello there! I love tests!"
. If I change the handler
function so that it reads
func handler (w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "I guess %s are ok...", r.URL.Path[1:])
}
I see the Starting up...
message printed in terminal again, but going to localhost:8080/tests
still gives me the page showing "Hello there! I love tests!"
(even in incognito mode). If I then kill the entr
process and restart it, I can go to localhost:8080/tests
to see I guess tests are ok...
as expected.
Edit:
Getting the error out of ListenAndServe
confirms that this has to do with a dangling socket.
...
err := http.ListenAndServe(":8080", nil)
fmt.Printf("ListenAndServe ERR: %s\n", err)
...
shows the extra line
listen tcp :8080: bind: address already in use
in terminal. A quick search tells me that there isn't an easy way to stop a listener started with ListenAndServe
. Is there a simpler approach than this?
go list -f '{{join .GoFiles " "}}'
is probably safer than using*.go
to eitherls
orgo run
(e.g. that will skip*_test.go
files and honor build constraints). You should probably also be usinggo build
instead ofgo run
(orgo build && ./yourProgName
).