LoginSignup
2
1

More than 3 years have passed since last update.

GoでHTTPサーバを立ち上げる(超基礎)

Posted at

GoでHTTPサーバを立ち上げる

server.go
package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "HTTPserver")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

ハンドラを定義する

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "HTTPserver")
}

・1つ目の引数:レスポンス先
・2つ目の引数:リクエストの受付
・{ }内はハンドラで行う処理内容

ハンドラとエントリポイントを結びつけ

 http.HandleFunc("/", handler)

・1つ目の引数:エントリポイント
・2つ目の引数:呼び出したいハンドラ

サーバの立ち上げ

 http.ListenAndServe(":8080", nil)

・1つ目の引数でポート番号を決める

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1