Reputation: 36404
I followed the example on Go docs and compiled this code for a Go server:
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
But when I access localhost:8080 it doesn't show up anything.
Upvotes: 1
Views: 4930
Reputation: 19408
Change http.ListenAndServe(":8080", nil)
to
if err := http.ListenAndServe("localhost:8080", nil); err != nil {
log.Fatal("ListenAndServe: ", err)
}
This will force the server to only listen on the localhost
interface and you won't have problems with permissions and firewall rules. It also logs any errors you may encounter.
Upvotes: 5
Reputation: 6610
In linux you need permission to run the program, because it is need listen on 8080 port.
I am using Ubuntu, and I ran go build -o main
, then I run sudo ./main
, when I access the localhost:8080 it shows Hi there, I love !
Upvotes: -1