ludwig125のブログ

頑張りすぎずに頑張る父

ローカルPCでGoでserverを立ち上げたときにファイアウォールを出なくさせる

困ってたこと

Goのサンプルプログラムで作ったサーバをローカルPCで起動させたいときに、 毎回ポップアップがでて うっとうしくて困っていた。

サーバ

例えばこういうの

package main

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

func main() {
    helloHandler := func(w http.ResponseWriter, req *http.Request) {
        fmt.Fprintf(w, "Hello\n")
    }

    http.HandleFunc("/hello", helloHandler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

ポップアップの内容

Windowsの場合(main.goというプログラムでサーバを起動させたときの例) ※WSLで実行

image

Macの場合(sample.goというプログラムでサーバを起動させたときの例)

image

  • 「アプリケーション 〇〇へのネットワーク受信接続を許可しますか?」

解決法

ListenAndServeのport番号の前に"127.0.0.1"または"localhost"を書くと、リクエストをlocalhostからのみに制限することができる。

こうすると外部からリクエストできなくなるので、ファイアウォールがブロックしないようになる。

この部分:http.ListenAndServe("127.0.0.1:8000", nil)

修正後のプログラム

package main

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

func main() {
    helloHandler := func(w http.ResponseWriter, req *http.Request) {
        fmt.Fprintf(w, "Hello\n")
    }

    http.HandleFunc("/hello", helloHandler)
    log.Fatal(http.ListenAndServe("localhost:8080", nil))
}

解説

https://golang.org/pkg/net/#Dial

For TCP, UDP and IP networks, if the host is empty or a literal unspecified IP address, as in ":80", "0.0.0.0:80" or "[::]:80" for TCP and UDP, "", "0.0.0.0" or "::" for IP, the local system is assumed.

-> ポートの前のホストが空の場合(例えば :80 のような場合)は 0.0.0.0 つまりどのホストからでもアクセスを受け付ける状態だと判断される

参考: