DEV Community

Shootacean
Shootacean

Posted on • Edited on • Originally published at shootacean.com

1

Goの標準ライブラリでWebサーバーを立ててHello, Worldする

Goの標準ライブラリ net/http を利用すれば、簡単にWebサーバーを実装することができます。

# goファイルを作成する
$ touch server.go
Enter fullscreen mode Exit fullscreen mode

以下のような、コードを書くことでWebサーバーを実装できます。

package main

import (
    "fmt"
    "net/http"
)

func main() {
    // ルーティングを設定する
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, World")
    })
    // ポート8080番でサーバーを起動する
    if err := http.ListenAndServe(":8080", nil); err != nil {
        panic(err)
    }
}
Enter fullscreen mode Exit fullscreen mode

以下のコマンドを実行後、ブラウザなどで

http://localhost:8080

にアクセスすると、Hello, Worldが出力されます。

$ go run server.go
Enter fullscreen mode Exit fullscreen mode

上記コマンドを実行した際とは別のターミナルセッションで、curlコマンドでアクセスしてみます

$ curl localhost:8080
Hello, World
Enter fullscreen mode Exit fullscreen mode

以上、Goの標準ライブラリ net/httpでWebサーバーを建てて、Hello, Worldする手順でした。

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay