func startBeego() {
	beego.BConfig.RunMode = beego.PROD
	beego.BeeLogger.Close()
	mux := beego.NewControllerRegister()
	mux.Get("/hello", beegoHandler)
	http.ListenAndServe(":"+strconv.Itoa(port), mux)
}
Beispiel #2
0
func Test_AuthRequestWithAuthorizationHeader(t *testing.T) {

	url := "/foo"

	mux := beego.NewControllerRegister()

	mux.InsertFilter("*", beego.BeforeRouter, AuthRequest(&Options{
		PrivateKeyPath: "test/jwt.rsa",
		PublicKeyPath:  "test/jwt.rsa.pub",
		WhiteList:      []string{"/v1/jwt/issue-token", "/docs"},
	}))

	mux.Add("/foo", &JwtController{}, "get:Foo")
	newToken := CreateToken()

	rw, r := testRequest("GET", url)
	r.Header.Add("Authorization", "Bearer "+newToken["token"])
	mux.ServeHTTP(rw, r)

	if rw.Code != http.StatusOK {
		t.Errorf("Shoud return 200")
	}
	if rw.Body.String() != "ok" {
		t.Errorf("Should output ok")
	}
}
Beispiel #3
0
// Tests the error message rendered as JSON
func (suite *TestNqmSuite) TestErrorMessage(c *C) {
	testedService := beego.NewControllerRegister()
	setupUrlMappingAndHandler(testedService)

	/**
	 * Sets-up HTTP request and response
	 */
	sampleRequest, err := http.NewRequest(http.MethodGet, "/nqm/icmp/list/by-provinces?dsl=v1%3D10", nil)
	c.Assert(err, IsNil)
	respRecorder := httptest.NewRecorder()
	// :~)

	testedService.ServeHTTP(respRecorder, sampleRequest)
	c.Logf("Response: %v", respRecorder)

	/**
	 * Asserts the status code of HTTP
	 */
	c.Assert(respRecorder.Code, Equals, 400)
	// :~)

	testedJsonBody := jsonDslError{}
	json.Unmarshal(respRecorder.Body.Bytes(), &testedJsonBody)

	/**
	 * Asserts the JSON body for error message
	 */
	c.Assert(testedJsonBody.Code, Equals, 1)
	c.Assert(testedJsonBody.Message, Matches, ".+Unknown parameter.+")
	// :~)
}
Beispiel #4
0
func Benchmark_WithoutCORS(b *testing.B) {
	recorder := httptest.NewRecorder()
	handler := beego.NewControllerRegister()
	beego.RunMode = "prod"
	handler.Any("/foo", func(ctx *context.Context) {
		ctx.Output.SetStatus(500)
	})
	b.ResetTimer()
	for i := 0; i < 100; i++ {
		r, _ := http.NewRequest("PUT", "/foo", nil)
		handler.ServeHTTP(recorder, r)
	}
}
Beispiel #5
0
Datei: nqm.go Projekt: donh/query
func configNqmRoutes() {
	nqmService = nqm.GetDefaultServiceController()
	nqmService.Init()

	/**
	 * Registers the handler of RESTful service on beego
	 */
	serviceController := beego.NewControllerRegister()
	setupUrlMappingAndHandler(serviceController)
	// :~)

	http.Handle("/nqm/", serviceController)
}
Beispiel #6
0
func Test_AllowAll(t *testing.T) {
	recorder := httptest.NewRecorder()
	handler := beego.NewControllerRegister()
	handler.InsertFilter("*", beego.BeforeRouter, Allow(&Options{
		AllowAllOrigins: true,
	}))
	handler.Any("/foo", func(ctx *context.Context) {
		ctx.Output.SetStatus(500)
	})
	r, _ := http.NewRequest("PUT", "/foo", nil)
	handler.ServeHTTP(recorder, r)

	if recorder.HeaderMap.Get(headerAllowOrigin) != "*" {
		t.Errorf("Allow-Origin header should be *")
	}
}
func loadBeegoSingle(method, path string, handler beego.FilterFunc) http.Handler {
	app := beego.NewControllerRegister()
	switch method {
	case "GET":
		app.Get(path, handler)
	case "POST":
		app.Post(path, handler)
	case "PUT":
		app.Put(path, handler)
	case "PATCH":
		app.Patch(path, handler)
	case "DELETE":
		app.Delete(path, handler)
	default:
		panic("Unknow HTTP method: " + method)
	}
	return app
}
Beispiel #8
0
func Test_DefaultAllowHeaders(t *testing.T) {
	recorder := httptest.NewRecorder()
	handler := beego.NewControllerRegister()
	handler.InsertFilter("*", beego.BeforeRouter, Allow(&Options{
		AllowAllOrigins: true,
	}))
	handler.Any("/foo", func(ctx *context.Context) {
		ctx.Output.SetStatus(500)
	})

	r, _ := http.NewRequest("PUT", "/foo", nil)
	handler.ServeHTTP(recorder, r)

	headersVal := recorder.HeaderMap.Get(headerAllowHeaders)
	if headersVal != "Origin,Accept,Content-Type,Authorization" {
		t.Errorf("Allow-Headers is expected to be Origin,Accept,Content-Type,Authorization; found %v", headersVal)
	}
}
Beispiel #9
0
func Test_AllowRegexNoMatch(t *testing.T) {
	recorder := httptest.NewRecorder()
	handler := beego.NewControllerRegister()
	handler.InsertFilter("*", beego.BeforeRouter, Allow(&Options{
		AllowOrigins: []string{"https://*.foo.com"},
	}))
	handler.Any("/foo", func(ctx *context.Context) {
		ctx.Output.SetStatus(500)
	})
	origin := "https://ww.foo.com.evil.com"
	r, _ := http.NewRequest("PUT", "/foo", nil)
	r.Header.Add("Origin", origin)
	handler.ServeHTTP(recorder, r)

	headerValue := recorder.HeaderMap.Get(headerAllowOrigin)
	if headerValue != "" {
		t.Errorf("Allow-Origin header should not exist, found %v", headerValue)
	}
}
Beispiel #10
0
func Test_Preflight(t *testing.T) {
	recorder := NewRecorder()
	handler := beego.NewControllerRegister()
	handler.InsertFilter("*", beego.BeforeRouter, Allow(&Options{
		AllowAllOrigins: true,
		AllowMethods:    []string{"PUT", "PATCH"},
		AllowHeaders:    []string{"Origin", "X-whatever", "X-CaseSensitive"},
	}))

	handler.Any("/foo", func(ctx *context.Context) {
		ctx.Output.SetStatus(200)
	})

	r, _ := http.NewRequest("OPTIONS", "/foo", nil)
	r.Header.Add(headerRequestMethod, "PUT")
	r.Header.Add(headerRequestHeaders, "X-whatever, x-casesensitive")
	handler.ServeHTTP(recorder, r)

	headers := recorder.Header()
	methodsVal := headers.Get(headerAllowMethods)
	headersVal := headers.Get(headerAllowHeaders)
	originVal := headers.Get(headerAllowOrigin)

	if methodsVal != "PUT,PATCH" {
		t.Errorf("Allow-Methods is expected to be PUT,PATCH, found %v", methodsVal)
	}

	if !strings.Contains(headersVal, "X-whatever") {
		t.Errorf("Allow-Headers is expected to contain X-whatever, found %v", headersVal)
	}

	if !strings.Contains(headersVal, "x-casesensitive") {
		t.Errorf("Allow-Headers is expected to contain x-casesensitive, found %v", headersVal)
	}

	if originVal != "*" {
		t.Errorf("Allow-Origin is expected to be *, found %v", originVal)
	}

	if recorder.Code != http.StatusOK {
		t.Errorf("Status code is expected to be 200, found %d", recorder.Code)
	}
}
Beispiel #11
0
func Test_OtherHeaders(t *testing.T) {
	recorder := httptest.NewRecorder()
	handler := beego.NewControllerRegister()
	handler.InsertFilter("*", beego.BeforeRouter, Allow(&Options{
		AllowAllOrigins:  true,
		AllowCredentials: true,
		AllowMethods:     []string{"PATCH", "GET"},
		AllowHeaders:     []string{"Origin", "X-whatever"},
		ExposeHeaders:    []string{"Content-Length", "Hello"},
		MaxAge:           5 * time.Minute,
	}))
	handler.Any("/foo", func(ctx *context.Context) {
		ctx.Output.SetStatus(500)
	})
	r, _ := http.NewRequest("PUT", "/foo", nil)
	handler.ServeHTTP(recorder, r)

	credentialsVal := recorder.HeaderMap.Get(headerAllowCredentials)
	methodsVal := recorder.HeaderMap.Get(headerAllowMethods)
	headersVal := recorder.HeaderMap.Get(headerAllowHeaders)
	exposedHeadersVal := recorder.HeaderMap.Get(headerExposeHeaders)
	maxAgeVal := recorder.HeaderMap.Get(headerMaxAge)

	if credentialsVal != "true" {
		t.Errorf("Allow-Credentials is expected to be true, found %v", credentialsVal)
	}

	if methodsVal != "PATCH,GET" {
		t.Errorf("Allow-Methods is expected to be PATCH,GET; found %v", methodsVal)
	}

	if headersVal != "Origin,X-whatever" {
		t.Errorf("Allow-Headers is expected to be Origin,X-whatever; found %v", headersVal)
	}

	if exposedHeadersVal != "Content-Length,Hello" {
		t.Errorf("Expose-Headers are expected to be Content-Length,Hello. Found %v", exposedHeadersVal)
	}

	if maxAgeVal != "300" {
		t.Errorf("Max-Age is expected to be 300, found %v", maxAgeVal)
	}
}
Beispiel #12
0
func Benchmark_WithCORS(b *testing.B) {
	recorder := httptest.NewRecorder()
	handler := beego.NewControllerRegister()
	beego.RunMode = "prod"
	handler.InsertFilter("*", beego.BeforeRouter, Allow(&Options{
		AllowAllOrigins:  true,
		AllowCredentials: true,
		AllowMethods:     []string{"PATCH", "GET"},
		AllowHeaders:     []string{"Origin", "X-whatever"},
		MaxAge:           5 * time.Minute,
	}))
	handler.Any("/foo", func(ctx *context.Context) {
		ctx.Output.SetStatus(500)
	})
	b.ResetTimer()
	for i := 0; i < 100; i++ {
		r, _ := http.NewRequest("PUT", "/foo", nil)
		handler.ServeHTTP(recorder, r)
	}
}
Beispiel #13
0
func Test_AuthRequestWithoutAuthorizationHeader(t *testing.T) {
	url := "/foo"

	mux := beego.NewControllerRegister()

	mux.InsertFilter("*", beego.BeforeRouter, AuthRequest(&Options{
		PrivateKeyPath: "test/jwt.rsa",
		PublicKeyPath:  "test/jwt.rsa.pub",
		WhiteList:      []string{"/v1/jwt/issue-token", "/docs"},
	}))

	mux.Add("/foo", &JwtController{}, "get:Foo")

	rw, r := testRequest("GET", url)
	mux.ServeHTTP(rw, r)

	if rw.Code != http.StatusUnauthorized {
		t.Errorf("Shoud return 401")
	}
}
func loadBeego(routes []route) http.Handler {
	re := regexp.MustCompile(":([^/]*)")
	app := beego.NewControllerRegister()
	for _, route := range routes {
		route.path = re.ReplaceAllString(route.path, ":$1")
		switch route.method {
		case "GET":
			app.Get(route.path, beegoHandler)
		case "POST":
			app.Post(route.path, beegoHandler)
		case "PUT":
			app.Put(route.path, beegoHandler)
		case "PATCH":
			app.Patch(route.path, beegoHandler)
		case "DELETE":
			app.Delete(route.path, beegoHandler)
		default:
			panic("Unknow HTTP method: " + route.method)
		}
	}
	return app
}