emahiro/b.log

Drastically Repeat Yourself !!!!

【続】FWに頼らないオレオレroutingを実装する

前回書いた記事の中でオレオレroutingを実装する際に標準の net/http パッケージだけだと足りないと書いてましたがこれ、間違いでした。

ema-hiro.hatenablog.com

標準の net/http パッケージだけでオレオレroutingを実装する方法は以下

main.go

package main

import (
    "gothub/handler"

    "fmt"
    "net/http"

    "github.com/labstack/gommon/log"
)

const port = "8080"

func main() {
    router := http.NewServeMux()
    router.HandleFunc("/", handler.Top)
    if err := http.ListenAndServe(fmt.Sprintf(":%s", port), router); err != nil {
        log.Fatal("err: %v", err)
    }
}

handler/handler.go

pakage handler

import (
    "net/http"
)

func Top(w http.ResponseWriter, r *httpRequest){
    // serverの処理
}

router := http.NewServeMux()HTTP Request multiplexerインスタンス化し、routerとして扱う。
http requestをhandleしたいroutingのメソッドには http.ResponseWriterhttp.Request を引数に与える。

routingのライブラリを使うことなく、標準のHTTPパッケージだけでもやりたかった、超薄いAPIを作るということは可能でした。

(golangのhttpパッケージすげぇ強力だなぁ(小並感))