Пример #1
0
func TestRouter(t *testing.T) {
	var path = "/aa/bb"
	var req, err = http.NewRequest("GET", "http://www.baidu.com"+path, nil)
	if err != nil {
		t.Error(err.Error())
	}
	var w http.ResponseWriter
	var ctx = context.NewContext(w, req)
	var r = NewRouter("/{a}/{b}", &TestHandler{})
	h, ok := r.Match(ctx)
	assert.True(t, ok)
	assert.NotNil(t, h)
	assert.Equal(t, ctx.Params[`a`], `aa`)
}
Пример #2
0
func (server *app) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var c = context.NewContext(w, r)

	var h handler.HandlerInterface
	if r, ok := server.routerMap[r.URL.Path]; ok {
		h, ok = r.Match(c)
	} else {
		for _, r := range server.routers {
			if h, ok = r.Match(c); ok {
				break
			}
		}
	}
	if h != nil {
		b := h
		if ParseBody {
			c.ParseBody()
		}
		defer b.OnFinally(c)

		b.OnBefore(c)

		switch c.Request.Method {
		case GET:
			b.Get(c)
		case POST:
			b.Post(c)
		case PUT:
			b.Put(c)
		case DELETE:
			b.Delete(c)
		case HEAD:
			b.Head(c)
		case OPTIONS:
			b.Options(c)
		default:
			b.NotFound(c)
		}

		b.OnAfter(c)

	} else {
		if server.NotFound != nil {
			server.NotFound(c)
		}
	}
}