Ejemplo n.º 1
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.º 2
0
// ExpvarHandler dumps json representation of expvars to http response.
//
// Expvars may be filtered by regexp provided via 'r' query argument.
//
// See https://golang.org/pkg/expvar/ for details.
func ExpvarHandler(ctx *fasthttp.RequestCtx) {
	expvarHandlerCalls.Add(1)

	ctx.Response.Reset()

	r, err := getExpvarRegexp(ctx)
	if err != nil {
		expvarRegexpErrors.Add(1)
		fmt.Fprintf(ctx, "Error when obtaining expvar regexp: %s", err)
		ctx.SetStatusCode(fasthttp.StatusBadRequest)
		return
	}

	fmt.Fprintf(ctx, "{\n")
	first := true
	expvar.Do(func(kv expvar.KeyValue) {
		if r.MatchString(kv.Key) {
			if !first {
				fmt.Fprintf(ctx, ",\n")
			}
			first = false
			fmt.Fprintf(ctx, "\t%q: %s", kv.Key, kv.Value)
		}
	})
	fmt.Fprintf(ctx, "\n}\n")

	ctx.SetContentType("application/json; charset=utf-8")
}
Ejemplo n.º 3
0
// ServerHTTP writes a redirect to an HTTP response
func (r *ProxyHandler) ServeHTTP(ctx *fasthttp.RequestCtx) {
	proxyClient := &fasthttp.HostClient{
		Addr: r.url,
		// set other options here if required - most notably timeouts.
	}

	req := &ctx.Request
	resp := &ctx.Response
	if err := proxyClient.Do(req, resp); err != nil {
		ctx.Logger().Printf("error when proxying the request: %s", err)
		ctx.SetStatusCode(fasthttp.StatusServiceUnavailable)
	}
}
Ejemplo n.º 4
0
// ResJSON 响应Json数据
func (fs *FastServer) ResJSON(ctx *fasthttp.RequestCtx, ti oauth2.TokenInfo) (err error) {
	data := map[string]interface{}{
		"access_token": ti.GetAccess(),
		"token_type":   fs.cfg.TokenType,
		"expires_in":   ti.GetAccessExpiresIn() / time.Second,
	}
	if scope := ti.GetScope(); scope != "" {
		data["scope"] = scope
	}
	if refresh := ti.GetRefresh(); refresh != "" {
		data["refresh_token"] = refresh
	}
	buf, err := json.Marshal(data)
	if err != nil {
		return
	}
	ctx.Response.Header.Set("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate")
	ctx.Response.Header.Set("Pragma", "no-cache")
	ctx.Response.Header.Set("Expires", "Fri, 01 Jan 1990 00:00:00 GMT")
	ctx.SetContentType("application/json;charset=UTF-8")
	ctx.SetStatusCode(200)
	_, err = ctx.Write(buf)
	return nil
}
Ejemplo n.º 5
0
func zingAlbumHandler(ctx *fasthttp.RequestCtx, params fasthttprouter.Params) {
	zingURL := string(ctx.QueryArgs().Peek("url"))
	log.Info("Zing-mp3 album request",
		"zing_url", zingURL,
	)

	album, err := zing.ParseAlbumData(zingURL)
	if err != nil {
		ctx.SetStatusCode(fasthttp.StatusBadRequest)
		fmt.Fprint(ctx, err)
		return
	}

	job, err := newAlbumJob(album, ctx.Response.BodyWriter())
	if err != nil {
		ctx.SetStatusCode(fasthttp.StatusInternalServerError)
		fmt.Fprint(ctx, err)
		return
	}

	ctx.SetStatusCode(fasthttp.StatusOK)
	job.Run()
}
Ejemplo n.º 6
0
// Handler makes the router implement the fasthttp.ListenAndServe interface.
func (r *Router) Handler(ctx *fasthttp.RequestCtx) {
	if r.PanicHandler != nil {
		defer r.recv(ctx)
	}

	path := string(ctx.Path())
	method := string(ctx.Method())
	if root := r.trees[method]; root != nil {
		if f, ps, tsr := root.getValue(path); f != nil {
			f(ctx, ps)
			return
		} else if method != "CONNECT" && path != "/" {
			code := 301 // Permanent redirect, request with GET method
			if method != "GET" {
				// Temporary redirect, request with same method
				// As of Go 1.3, Go does not support status code 308.
				code = 307
			}

			if tsr && r.RedirectTrailingSlash {
				var uri string
				if len(path) > 1 && path[len(path)-1] == '/' {
					uri = path[:len(path)-1]
				} else {
					uri = path + "/"
				}
				ctx.Redirect(uri, code)
				return
			}

			// Try to fix the request path
			if r.RedirectFixedPath {
				fixedPath, found := root.findCaseInsensitivePath(
					CleanPath(path),
					r.RedirectTrailingSlash,
				)
				if found {
					uri := string(fixedPath)
					ctx.Redirect(uri, code)
					return
				}
			}
		}
	}

	if method == "OPTIONS" {
		// Handle OPTIONS requests
		if r.HandleOPTIONS {
			if allow := r.allowed(path, method); len(allow) > 0 {
				ctx.Response.Header.Set("Allow", allow)
				return
			}
		}
	} else {
		// Handle 405
		if r.HandleMethodNotAllowed {
			if allow := r.allowed(path, method); len(allow) > 0 {
				ctx.Response.Header.Set("Allow", allow)
				if r.MethodNotAllowed != nil {
					r.MethodNotAllowed(ctx)
				} else {
					ctx.SetStatusCode(fasthttp.StatusMethodNotAllowed)
					ctx.SetContentTypeBytes(defaultContentType)
					ctx.SetBodyString(fasthttp.StatusMessage(fasthttp.StatusMethodNotAllowed))
				}
				return
			}
		}
	}

	// Handle 404
	if r.NotFound != nil {
		r.NotFound(ctx)
	} else {
		ctx.Error(fasthttp.StatusMessage(fasthttp.StatusNotFound),
			fasthttp.StatusNotFound)
	}
}
Ejemplo n.º 7
0
// Write outputs the header content.
func (h Head) Write(ctx *fasthttp.RequestCtx) {
	ctx.Response.Header.Set(ContentType, h.ContentType)
	ctx.SetStatusCode(h.Status)
}
Ejemplo n.º 8
0
func (b *blockAction) Act(_ string, ctx *fasthttp.RequestCtx) error {
	ctx.SetStatusCode(429)
	ctx.Write(b.message)
	return nil
}
Ejemplo n.º 9
0
func status404(ctx *fasthttp.RequestCtx) {
	ctx.SetStatusCode(fasthttp.StatusNotFound)
	ctx.WriteString("Image not found!")
}