Ejemplo n.º 1
0
func TestInvalidParams(t *testing.T) {
	s, ln, srverr := startServer()
	defer stopServer(s, ln, srverr)
	response := fasthttp.AcquireResponse()
	request := fasthttp.AcquireRequest()
	base := fmt.Sprintf("http://localhost:%d/", port) + "testimages/server/01.jpg"
	cases := []string{
		"?width=abc&height=200",
		"?width=200&height=abc",
		"?width=200?height=200",
		"?width=200&height=200&mode=fit&something=x",
		"?width=200&height=200&mode=y",
		"?format=abc"}

	for _, c := range cases {
		uri := base + c
		request.SetRequestURI(uri)
		fasthttp.Do(request, response)
		if response.Header.StatusCode() != 400 {
			t.Fatal("Server did not return 400 to request: " + uri)
		}
		request.Reset()
		response.Reset()
	}
	fasthttp.ReleaseRequest(request)
	fasthttp.ReleaseResponse(response)
}
Ejemplo n.º 2
0
func BenchmarkProxyHandlerBlockWithMatchingRegexRule(b *testing.B) {
	var handler http.Handler = &testServer{}
	s := httptest.NewServer(handler)
	defer s.Close()
	rs := make([]*rule.Rule, 0)
	r := &rule.Rule{}

	r.Filters = make([]*selector.Selector, 0, 1)
	sel, _ := selector.Parse("IP=.*")
	r.Filters = append(r.Filters, sel)

	r.Actions = make([]action.Action, 0, 1)
	a, _ := action.Create("block", make(action.ActionParams))
	r.Actions = append(r.Actions, a)

	rs = append(rs, r)
	p := &Proxy{
		NumberOfRequests: 0,
		target:           []byte(s.URL),
		Rules:            &rs,
	}
	b.ResetTimer()
	ctx := &fasthttp.RequestCtx{}
	ctx.Request = *fasthttp.AcquireRequest()
	ctx.Init(&ctx.Request, nil, nil)
	defer fasthttp.ReleaseRequest(&ctx.Request)
	for i := 0; i < b.N; i++ {
		p.Handler(ctx)
	}
}
Ejemplo n.º 3
0
func (p *Proxy) Handler(ctx *fasthttp.RequestCtx) {

	respState := rule.Evaluate(p.Rules, ctx)
	if respState == types.SERVED {
		return
	}

	appRequest := fasthttp.AcquireRequest()
	defer fasthttp.ReleaseRequest(appRequest)
	appRequest.Header.SetMethodBytes(ctx.Method())
	ctx.Request.Header.CopyTo(&appRequest.Header)
	if ctx.IsPost() || ctx.IsPut() {
		appRequest.SetBody(ctx.PostBody())
	}

	resp := fasthttp.AcquireResponse()
	defer fasthttp.ReleaseResponse(resp)
	err := p.client.Do(appRequest, resp)
	if err != nil {
		log.Println("Response error:", err, resp)
		ctx.SetStatusCode(429)
		return
	}

	resp.Header.CopyTo(&ctx.Response.Header)

	ctx.SetStatusCode(resp.StatusCode())

	resp.BodyWriteTo(ctx)
}
Ejemplo n.º 4
0
// KeepAlive for support connect, session key will available for 20 minutes
func (b *Betting) KeepAlive() error {
	var keepAlive *KeepAlive = &KeepAlive{}

	req, resp := fasthttp.AcquireRequest(), fasthttp.AcquireResponse()
	req.SetRequestURI(KeepAliveURL)
	req.Header.Set("Accept", "application/json")
	req.Header.Set("X-Application", b.ApiKey)
	req.Header.Set("X-Authentication", b.SessionKey)
	req.Header.SetMethod("POST")

	err := fasthttp.Do(req, resp)
	if err != nil {
		return err
	}

	err = json.Unmarshal(resp.Body(), keepAlive)
	if err != nil {
		return err
	}

	switch keepAlive.Status {
	case "SUCCESS":
		b.SessionKey = keepAlive.Token
	default:
		err = errors.New(keepAlive.Error)
	}

	return err
}
Ejemplo n.º 5
0
// Test for right content-type request header
func TestMIMEtype(t *testing.T) {
	s, ln, srverr := startServer()
	defer stopServer(s, ln, srverr)
	response := fasthttp.AcquireResponse()
	request := fasthttp.AcquireRequest()
	cases := []string{"", "?format=jpeg", "?format=png", "?format=webp", "?format=tiff", "?format=bmp", "?format=gif"}
	folder := "testimages/server/"

	for _, c := range cases {
		request.SetRequestURI(fmt.Sprintf("http://localhost:%d/", port) + folder + "01.jpg" + c)
		fasthttp.Do(request, response)
		MIME := string(response.Header.ContentType())

		img := images.NewImage()
		img.FromBlob(response.Body())
		expected := "image/" + strings.ToLower(img.GetImageFormat())

		if MIME != expected {
			t.Fatal(fmt.Sprintf("Server returned: %s, image is %s", MIME, expected))
		}
		request.Reset()
		response.Reset()
		img.Destroy()
	}
	fasthttp.ReleaseRequest(request)
	fasthttp.ReleaseResponse(response)
}
Ejemplo n.º 6
0
func client(configuration *Configuration, result *Result, done *sync.WaitGroup) {
	for result.requests < configuration.requests {
		for _, tmpUrl := range configuration.urls {

			req := fasthttp.AcquireRequest()

			req.SetRequestURI(tmpUrl)
			req.Header.SetMethodBytes([]byte(configuration.method))

			if configuration.keepAlive == true {
				req.Header.Set("Connection", "keep-alive")
			} else {
				req.Header.Set("Connection", "close")
			}

			if len(configuration.authHeader) > 0 {
				req.Header.Set("Authorization", configuration.authHeader)
			}

			if len(configuration.contentType) > 0 {
				req.Header.Set("Content-Type", contentType)

			} else if len(configuration.postData) > 0 {
				req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
			}

			req.SetBody(configuration.postData)

			resp := fasthttp.AcquireResponse()
			err := configuration.myClient.Do(req, resp)
			statusCode := resp.StatusCode()
			result.requests++
			fasthttp.ReleaseRequest(req)
			fasthttp.ReleaseResponse(resp)

			if err != nil {
				fmt.Printf("Network error: %s\n", err)
				result.networkFailed++
				continue
			}

			if statusCode == fasthttp.StatusOK {
				result.success++
			} else {
				result.badFailed++
			}
		}
	}

	done.Done()
}
Ejemplo n.º 7
0
func TestRequestAttrMatch(t *testing.T) {
	s, err := Parse("Path")
	if err != nil {
		t.Error(err)
		return
	}
	ctx := &fasthttp.RequestCtx{}
	ctx.Request = *fasthttp.AcquireRequest()
	defer fasthttp.ReleaseRequest(&ctx.Request)
	ctx.Request.SetRequestURI("http://127.0.0.1/x?y=z")
	if path, found := s.Match(ctx); found != true || path != "/x" {
		t.Error("Path \"/x\" not found:", path)
	}
}
Ejemplo n.º 8
0
// Request function for send requests to betfair via REST JSON
func (b *Betting) Request(reqStruct interface{}, url BetURL, method string, filter *Filter) error {
	req, resp := fasthttp.AcquireRequest(), fasthttp.AcquireResponse()

	urlBuild := bytes.NewBuffer([]byte{})
	urlBuild.WriteString(string(url))
	urlBuild.WriteString("/")
	urlBuild.WriteString(method)
	urlBuild.WriteString("/")

	req.SetRequestURI(urlBuild.String())
	req.Header.Set("Accept", "application/json")
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-Application", b.ApiKey)
	req.Header.Set("X-Authentication", b.SessionKey)
	req.Header.SetMethod("POST")

	if filter != nil {
		filterBody, err := ffjson.Marshal(&filter)
		if err != nil {
			return err
		}

		req.SetBody(filterBody)
	}

	err := fasthttp.Do(req, resp)
	if err != nil {
		return err
	}

	if resp.StatusCode() == 400 {
		err = ffjson.Unmarshal(resp.Body(), &bettingError)
		if err != nil {
			return err
		}

		return fmt.Errorf("Error with code - %s and string - %s", bettingError.Faultcode, bettingError.Faultstring)
	}

	err = ffjson.Unmarshal(resp.Body(), reqStruct)
	if err != nil {
		return err
	}

	return nil
}
Ejemplo n.º 9
0
func TestGETAttrMatch(t *testing.T) {
	s, err := Parse("GET:x=(y|z)")
	if err != nil {
		t.Error(err)
		return
	}
	ctx := &fasthttp.RequestCtx{}
	ctx.Request = *fasthttp.AcquireRequest()
	ctx.Request.SetRequestURI("http://127.0.0.1/?x=y")
	defer fasthttp.ReleaseRequest(&ctx.Request)
	if attr, found := s.Match(ctx); found != true || attr != "y" {
		t.Error("GET attribute not found")
	}
	ctx.Request.SetRequestURI("http://127.0.0.1/?x=a")
	if _, found := s.Match(ctx); found == true {
		t.Error("Found non existent attribute")
	}
}
Ejemplo n.º 10
0
func BenchmarkProxyHandlerWithoutRules(b *testing.B) {
	var handler http.Handler = &testServer{}
	s := httptest.NewServer(handler)
	defer s.Close()
	r := make([]*rule.Rule, 0)
	p := &Proxy{
		NumberOfRequests: 0,
		target:           []byte(s.URL),
		Rules:            &r,
	}
	ctx := &fasthttp.RequestCtx{}
	ctx.Request = *fasthttp.AcquireRequest()
	ctx.Init(&ctx.Request, nil, nil)
	defer fasthttp.ReleaseRequest(&ctx.Request)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		p.Handler(ctx)
	}
}
Ejemplo n.º 11
0
func (b *Betting) GetSession(pemCert, keyCert, login, password string) error {
	var session *Session = &Session{}

	cert, err := tls.LoadX509KeyPair(pemCert, keyCert)
	if err != nil {
		return err
	}

	client := fasthttp.Client{TLSConfig: &tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true}}

	req, resp := fasthttp.AcquireRequest(), fasthttp.AcquireResponse()
	req.SetRequestURI(CertURL)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("X-Application", b.ApiKey)
	req.Header.SetMethod("POST")

	bufferString := bytes.NewBuffer([]byte{})
	bufferString.WriteString(`username=`)
	bufferString.WriteString(login)
	bufferString.WriteString(`&password=`)
	bufferString.WriteString(password)

	req.SetBody(bufferString.Bytes())

	err = client.Do(req, resp)
	if err != nil {
		return err
	}

	err = json.Unmarshal(resp.Body(), session)
	if err != nil {
		return err
	}

	switch session.LoginStatus {
	case LS_SUCCESS:
		b.SessionKey = session.SessionToken
	default:
		err = errors.New(string(session.LoginStatus))
	}

	return err
}