Get golang http server working with rerun - go

I'm trying to use rerun to relaunch a go http server when the source files change, but the restart always fails to launch.
Simple server
package main
import (
"net/http"
"fmt"
"log"
"html"
)
func main() {
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
Command line output
$ rerun -p "**/*.{go,html}" go run my_server.go
16:49:24 [rerun] Rerun_test launched
16:49:26 [rerun] Watching . for **/*.{go,html} using Darwin adapter
16:50:17 [rerun] Change detected: 1 modified
16:50:17 [rerun] Sending signal TERM to 75688
16:50:17 [rerun] Rerun_test restarted
2014/07/15 16:50:17 listen tcp :8080: bind: address already in use
exit status 1
16:50:19 [rerun] Rerun_test Launch Failed
How can I get this working, or why can't the server bind to the port when it is relaunched?
Also, I am using OSX 10.9.

A process already running on port 8080 that's why it cannot re-run, go to your activity monitor find the process in your case it may be named as (my_server), and quit it.

Related

What causes urn:acme:error:unauthorized 403 error in golang's acme/autocert?

The full error message is:
403 urn:acme:error:unauthorized: Account creation on ACMEv1 is
disabled. Please upgrade your ACME client to a version that supports
ACMEv2 / RFC 8555. See
https://community.letsencrypt.org/t/end-of-life-plan-for-acmev1/88430
for details
And I've googled this and reviewed that link, but I'm just using:
golang.org/x/crypto/acme/autocert
package in a very normal way:
package main
import (
"crypto/tls"
"net/http"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/acme/autocert"
)
func main() {
router := gin.Default()
hosts := []string{"yourdomain.com"}
certManager := autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(hosts...),
Cache: autocert.DirCache("/certs"),
}
server := &http.Server{
Addr: ":https",
Handler: router,
TLSConfig: &tls.Config{
GetCertificate: certManager.GetCertificate,
},
}
server.ListenAndServeTLS("", "")
}
In fact this code has been running and working fine for the last 6 months. But just today I switched the server it was on and now get the above message.
I tried getting the very latest version of golang, but still same problem.
I changed my DNS for my hosts to this new server's ip and the hostname of the server is correct.
Far as I can tell, it's 100% identical to the previous working server but with a new IP.
Is golang's acme/autocert really this out of date and not using ACMEv2?
This statement:
In fact this code has been running and working fine for the last 6 months. But just today I switched the server it was on and now get the above message.
Might indicate that you're building against an older version of golang.org/x/crypto - check your go.mod file and ensure you're using a fairly recent version. I completed a project recently that uses almost identical code. The require in my go.mod looks like this:
golang.org/x/crypto v0.0.0-20200602180216-279210d13fed

gcloud app deploy says: exec: "git": executable file not found in $PATH

I am struggling to deploy a simple Go app to Google App Engine flexible environment. (This is a very cut-down version of a larger app.) When I run gcloud app deploy --project=<projectID> it terminates with an error, and has this in its output:
...
Step #0: Status: Downloaded newer image for gcr.io/gcp-runtimes/go1-builder#sha256:68b86e4c97438df4c9e36c55ad724079b453398a0a44c29748fb5685eef73895
Step #0: gcr.io/gcp-runtimes/go1-builder#sha256:68b86e4c97438df4c9e36c55ad724079b453398a0a44c29748fb5685eef73895
Step #0: go: github.com/go-stack/stack#v1.8.0: git init --bare in /workspace/_gopath/pkg/mod/cache/vcs/6963ea18be763686e7a9697733dd92bfcc0d45b687afce82da04992523d91cd1: exec: "git": executable file not found in $PATH
Step #0: go: github.com/inconshreveable/log15#v0.0.0-20200109203555-b30bc20e4fd1: git init --bare in /workspace/_gopath/pkg/mod/cache/vcs/fe2a07d0f4107d9daa39043733e909094a5b926cca44d0f7269e7a2185dbef15: exec: "git": executable file not found in $PATH
Step #0: go: github.com/mattn/go-colorable#v0.1.6: git init --bare in /workspace/_gopath/pkg/mod/cache/vcs/f7e99db597f4d2fe3e4509a9af308dace72a13292b505deb909cd0df29c1468a: exec: "git": executable file not found in $PATH
Step #0: go: error loading module requirements
Finished Step #0
It does work if I delete go.mod, but (I think) I need go.mod to compile and test it locally. It does work if I don't import the external package, but of course I need external packages in my larger app. It does work if I choose the standard environment, but I need the flexible environment for my larger app.
How can I deploy this app successfully to a flexible environment?
My local Go is 1.13, and I have the latest version (292.0.0) of gcloud. Apart from go.sum, the contents of my directory is...
app.yaml:
runtime: go1.12
env: flex
go.mod:
module mymodulename
go 1.13
require (
github.com/go-stack/stack v1.8.0 // indirect
github.com/inconshreveable/log15 v0.0.0-20200109203555-b30bc20e4fd1
github.com/mattn/go-colorable v0.1.6 // indirect
)
main.go:
package main
import (
"fmt"
"net/http"
"os"
"github.com/inconshreveable/log15"
)
func main() {
log := log15.New()
http.HandleFunc("/", helloHandler)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
log.Info("Using default port", "port", port)
}
log.Info("Listening", "port", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Crit("ListenAndServe", "error", err)
os.Exit(1)
}
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello, there")
}
Thank you.
IIUC Flexible doesn't support modules (Standard does, go figure!).
You can:
either use a custom runtime;
or, delete the go.mod|go.sum and try again.
I copied your app.yaml and main.go and it worked for me.
One change to your app.yaml:
runtime: go
env: flex
Then:
go get github.com/inconshreveable/log15
go run main.go
INFO[05-15|09:33:26] Using default port port=8080
INFO[05-15|09:33:26] Listening port=8080
and:
curl --silent http://localhost:8080
Hello, there
and:
gcloud app deploy --project=${PROJECT}
curl --silent $(\
gcloud app describe \
--project=${PROJECT} \
--format="value(defaultHostname)")
Hello, there

process interrupted: signal: killed

I installed a utility called watcher.
https://github.com/canthefason/go-watcher
It works as expected using VS code.
But when I tried to use it in Goland (from Jetbrains) I get the following:
watcher main.go --port 8080
2020/03/04 14:10:42 build started
Building ....
2020/03/04 14:10:43 build completed
Running ...
2020/03/04 14:10:43 process interrupted: signal: killed
Needless to say go run main.go --port 8080 works.
I use a MAC Catalina.
Any suggestions?
Looks like an error from cmd.Wait()
if err := cmd.Wait(); err != nil {
log.Printf("process interrupted: %s \n", err)
...
A similar report was the OS killing the process because it was out of memory (OOM), and dmesg might have logged the error.

Unable to create online web-page

I am trying to create Golang web-pages...
Progress:
Ubuntu 18.04 installed both locally and on a Linode VPS.
Created and compiled a local Golang "Hello World" script that renders OK both locally and online.
Created a net/http Golang script that works OK when called locally http://localhost:8080/testing to see if it works
Uploaded the script to the Linode server and initial status messages appear but when calling http:123.456.789.32:8080/testing to see if it works the browser freezes.
//
// Golang - main.go
//
package main
import (
"net/http"
)
func sayHello(w http.ResponseWriter, r *http.Request) {
message := r.URL.Path
message = "Hello " + message
w.Write([]byte(message))
}
func main() {
http.HandleFunc("/", sayHello)
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(err)
}
}
There are no errors or warnings rendered and unable to find any log references.
Can error and warnings similar to PHP error_reporting(-1), declare(strict_types=1) etc be logged or rendered?
A quick check with Nmap showed this result:
nmap -sV -p 8080 <yourIP>
Starting Nmap 7.70 ( https://nmap.org ) at 2019-07-04 07:45 CEST
Nmap scan report for <your-domain>.com (<yourIP>)
Host is up (0.032s latency).
PORT STATE SERVICE VERSION
8080/tcp filtered http-proxy
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 0.90 seconds
The state of "filtered" actually means that there was no response on that port as opposed to an outright rejection of the request.
Check the output of iptables -L -n. Presumably, you have a firewall running and blocking port 8080. Do not simply deactivate the firewall, but read up on how to open port 8080 in the firewall product you are using. Linode has guides for the commonly used/preinstalled firewalls of various Linux distributions.
If you plan to go into production, please have someone help you to ensure security and availability of your deployment.

http.ListenAndServe handler function executed twice on port 80 [duplicate]

This question already has answers here:
HandleFunc being called twice
(4 answers)
Why this simple web server is called even number times?
(1 answer)
Closed 5 years ago.
If I run the following simple http server code on port 8080 everything works as expected. If I run the same code on port 80, by just changing the port, the handler function is executed twice with each request. Why, and how to fix it?
// httptest project main.go
package main
import (
"net/http"
"log"
"fmt"
"html"
)
var count int
func defaultHandler(w http.ResponseWriter, r *http.Request) {
count++
fmt.Fprintf(w, "Hello, %q count=%d", html.EscapeString(r.URL.Path), count)
fmt.Println(count,r.RemoteAddr)
}
func main() {
http.HandleFunc("/", defaultHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
If I enter localhost:8080 in the browser, I get a response with a count starting at 1 and increased by 1 with each new request.
If I change the code to port 80 and enter just localhost or localhost:80 in the browser, I get a first response with a count starting at 1 but increased by two with each following request. At the same time the print statement for the console output is executed twice.
Terminal console when running on port 80 with 3 requests:
>go run main.go
1 [::1]:51335
2 [::1]:51335
3 [::1]:51335
4 [::1]:51335
5 [::1]:51335
6 [::1]:51335
The responses in the browser are Hello, "/" count=1, Hello, "/" count=3 and Hello, "/" count=5.
I've been running this locally on Windows 10 with Go version go1.9.2 windows/amd64 and the latest Google Chrome Browser.
However, I detected the issue in a simple web application on a remote Linux server where the code has been compiled with go version go1.9.1 linux/amd64.
i just tried it on my pc with Fiddler open
I noticed when navigating to the url using Google Chrome, the browser makes 2 request
GET / HTTP/1.1
GET /favicon.ico HTTP/1.1
the request for the favicon also gets handled by the defaultHandler, which causes the count to increment
I also tried with firefox and it doesn't send another request for the favicon
Try to log requests. Possibly browser is calling /favicon.ico

Resources