LoginSignup
0
0

More than 1 year has passed since last update.

[Go Snippet] シンプル HTTP サーバー

Last updated at Posted at 2021-07-24

基本

main.go
package main

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

func hello(w http.ResponseWriter, r *http.Request) {
    // io.WriteString(w, "hello, world!\n") or
    fmt.Fprint(w, "hello, world!\n")
}

func main() {
    http.HandleFunc("/hello", hello)
    log.Fatal(http.ListenAndServe(":8000", nil))
}

go run main.go の後、コンソールから curl http://localhost:8000/hello を実行すると、hello, world! が返ってくる

ただ、POST で送信しても同様の結果になる (curl -X POST http://localhost:8000/hello)

リクエストメソッドで出力変える

GETPOST でレスポンスを変えるには、r.Method をチェックする必要がある

package main

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

func hello(w http.ResponseWriter, r *http.Request) {
    if r.Method == http.MethodGet {
        fmt.Fprint(w, "hello from GET\n")
    } else {
        fmt.Fprint(w, "hello from POST\n")
    }
}

func main() {
    http.HandleFunc("/hello", hello)
    log.Fatal(http.ListenAndServe(":8000", nil))
}

これで GETPOST のリクエストに応じてレスポンスを変えられる

fmt.Fprint or io.WriteString どっちを使う?

上記のサンプルでは、fmt.Fprintio.WriteString いずれでも問題なく動作するけど、結局何が違うの?
ということで、調べてみました。

関数 シグネチャ
io.WriteString func WriteString(w Writer, s string) (n int, err error)
fmt.Fprint func Fprint(w io.Writer, a ...interface{}) (n int, err error)

結論から言うと、文字列 を出力する場合は io.WriteString で、それ以外は、fmt.Fprint で OK。

fmt.Fprint の方が、複数の引数を渡せたり、型に縛られずに渡すことができる汎用性がある。

0
0
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
0
0