0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Go Snippet] マルチプレクサをざっくり

Posted at

自作で ServeHTTP を実装

http.Handler は、ServeHTTP を実装すれば OK。
(詳しくは「Golang での Web アプリ開発で、理解を早める 5 ステップ」をチェック)

maing.go
package main

import (
	"fmt"
	"math/rand"
	"net/http"
)

type MyServeMux struct {
}

// ServeHTTP を implement
func (p *MyServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/" {
		fmt.Fprint(w, "hello, world!\n")
		return
	}
	if r.URL.Path == "/randomInt" {
		fmt.Fprintf(w, "Random number is: %d", rand.Int())
		return
	}

	// TOP 以外のパスがきたら Not Found を返す
	http.NotFound(w, r)
}

func main() {
	mux := &MyServeMux{}
	http.ListenAndServe(":8000", mux)
}

NewServeMux を使う

自作のマルチプレクサだと、if 文で URL パスをチェックしないといけない。
これだと手間なので、NewServeMus を使うことでもう少し簡単に書ける

main.go
package main
import (
    "fmt"
    "math/rand"
    "net/http"
)
func main() {
    myMux := http.NewServeMux()

    // TOP ページ    
    myMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, "hello, world!\n")
    })

    // random int ページ
    myMux.HandleFunc("/randomInt", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, rand.Int())
    })

    http.ListenAndServe(":8000", myMux)
}
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?