GolangWeb开发使用route路由包

route是博主开发的一个GolangWeb开发进行路由分配的一个路由包。特点是:精简、方便、强大。代码量只有70几行。

在路由层完美的支持restful架构

支持自动载入静态文件

支持自定义设置404处理函数

代码量不多,贴上实现代码:

//http路由分配器
package route

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

type Mux struct {
	handlers map[string][]*Handler
	NotFound http.HandlerFunc
	static string
}

type Handler struct {
	path  string
	http.HandlerFunc
}

func New(static string,NotFound http.HandlerFunc) *Mux {
	return &Mux{make(map[string][]*Handler), NotFound,static}
}

//开启http服务
func (m *Mux) Listen(port string) {
	err:=http.ListenAndServe(port, m)
	if err!=nil{
		log.Fatal("开启http服务错误!")
	}
}

//添加路由
func (m *Mux) add(mode, path string, fun http.HandlerFunc) {
	h := &Handler{
		strings.ToLower(path),
		fun}
	m.handlers[strings.ToLower(mode)] = append(
		m.handlers[strings.ToLower(mode)],
		h,
	)
}

//添加路由
func (m *Mux) AddRoute(mode string,path string,fun http.HandlerFunc) {
	m.add(mode,path,fun)
}

//设置404执行函数
func (this *Mux) SetNotFound(fun http.HandlerFunc) {
	this.NotFound=fun
}

//进行路由分配
func (m *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	url:=strings.Split(strings.TrimLeft(r.URL.Path,"/"),"/")
	if strings.ToLower(url[0])==strings.ToLower(m.static){
		http.ServeFile(w,r,"."+r.URL.Path)
		return
	}
	for _, handler := range m.handlers[strings.ToLower(r.Method)] {
		if handler.path == "/"+strings.ToLower(url[0]) {
			handler.ServeHTTP(w, r)
			return
		}
	}
	if m.NotFound != nil {
		w.WriteHeader(404)
		m.NotFound.ServeHTTP(w, r)
		return
	}
	http.NotFound(w, r)
}


Comments : 0

有问题可在下面发表评论,当然没事也可以在下面吹吹牛皮、扯扯淡!

发表评论

*


Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/blog/content/templates/Bitter/footer.php:40) in /www/wwwroot/blog/include/lib/view.php on line 23