dongnanbi4942 2019-01-25 15:40
浏览 46
已采纳

可以卷曲http服务器,但不能使用浏览器

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

  • 写回答

1条回答 默认 最新

  • doujiaozhan2413 2019-01-25 16:14
    关注

    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"。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化