1
1

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 1 year has passed since last update.

golangで、ちょー簡易URLルーター

Last updated at Posted at 2023-02-20

golangで簡易URLルーターを実装してみました

package parse

import (
	"net/http"
	"log"

	"net/url"
	"strings"
	
	"pdbg.work/hoge/module/setting"
)

var (
	param []string
)

func Parse(w http.ResponseWriter, r *http.Request) {
	// URLの取得
	u, err := url.Parse(r.URL.Path)
	if err != nil {
		log.Fatal(err)
	}
	
	// URLのパース
	param := strings.Split(strings.Trim(u.Path, "/"), "/")
	
	// paramのトリム
	for key, value := range param {
		param[key] = strings.TrimSpace(value)
	}
	
	// 実行
	if (param[0] == "exec") {
		f := param[1]
		param = param[2:]
		
		if (setting.Functions[f] != nil) {
			setting.Functions[f](w, r, param)
			
			return
		}
	}
	
	// ServeHTTPでhttp.FileServerの実行
	http.FileServer(http.Dir("public")).ServeHTTP(w, r)
}

 本当、簡易的なプログラムなのでソースリストを見た方が早いですけど

 http.ServerのHandler:でハンドラー設定を行い、parse.Parseを実行しています

 /settingのmap[string]func(w http.ResponseWriter, r *http.Request, param []string)型のmap変数で設定して、実行メゾッドsetting.Functions[f]を呼び出してます

 ServeHTTPでhttp.FileServerを実行している事で、staticなファイルへのアクセスも可能です

以上、よろしくお願いします(よろしく

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?