goweb-applicationsubuntu-18.04

curling http-server is ok but with the browser doesn't work


I'm just approaching webapps in Golang.

This is the simple code as starting point:

package main

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

const (
        CONN_HOST = "localhost"
        CONN_PORT = "8080"
)

func helloWorld(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello World!")
}

func main() {
        http.HandleFunc("/", helloWorld)
        err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, nil)
        if err != nil {
                log.Fatal("error starting http server : ", err)
                return
        }
}

Executing:

go run http-server.go

curl http://localhost:8080/
Hello World!

But when opening in a web-browser the ip-address:

http://111.111.1.1:8080/
connection didn't succeed

If I substitute this piece of code:

        err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, nil)
        if err != nil {
                log.Fatal("error starting http server : ", err)
                return
        }

with :

         log.Fatal(http.ListenAndServe(":8080", nil))

so the main() function is composed of just these 2 lines:

    func main() {
        http.HandleFunc("/", helloWorld)
    }

curl http://localhost:8080/
Hello World!

And in the web-browser:

http://111.111.1.1:8080/

Hello World!

So.... how to make the original simple http-server.go working in the web-browser and not only with commmand-line curl ? Looking forward to your kind help. Marco


Solution

  • The ip address your server listened to is localhost,so it only handled requests to localhost.

    You can try curl http://111.111.1.1:8080/, you would fail too.

    If you want to access you server from lan or any other IP, you should set CONN_HOST = "111.111.1.1"。