本文整理汇总了Golang中github.com/valyala/fasthttp.RequestCtx类的典型用法代码示例。如果您正苦于以下问题:Golang RequestCtx类的具体用法?Golang RequestCtx怎么用?Golang RequestCtx使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了RequestCtx类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: RoundTrip
// RoundTrip implements http.RoundTripper.RoundTrip.
func (binder FastBinder) RoundTrip(stdreq *http.Request) (*http.Response, error) {
var fastreq fasthttp.Request
convertRequest(stdreq, &fastreq)
var ctx fasthttp.RequestCtx
ctx.Init(&fastreq, nil, nil)
if stdreq.ContentLength >= 0 {
ctx.Request.Header.SetContentLength(int(stdreq.ContentLength))
} else {
ctx.Request.Header.Add("Transfer-Encoding", "chunked")
}
if stdreq.Body != nil {
b, err := ioutil.ReadAll(stdreq.Body)
if err == nil {
ctx.Request.SetBody(b)
}
}
binder.handler(&ctx)
return convertResponse(stdreq, &ctx.Response), nil
}
示例2: ExpvarHandler
// 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")
}
示例3: serveWebsocket
func (rp *FastReverseProxy) serveWebsocket(dstHost string, reqData *RequestData, ctx *fasthttp.RequestCtx) {
req := &ctx.Request
uri := req.URI()
uri.SetHost(dstHost)
dstConn, err := rp.dialFunc(dstHost)
if err != nil {
log.LogError(reqData.String(), string(uri.Path()), err)
return
}
if clientIP, _, err := net.SplitHostPort(ctx.RemoteAddr().String()); err == nil {
if prior := string(req.Header.Peek("X-Forwarded-For")); len(prior) > 0 {
clientIP = prior + ", " + clientIP
}
req.Header.Set("X-Forwarded-For", clientIP)
}
_, err = req.WriteTo(dstConn)
if err != nil {
log.LogError(reqData.String(), string(uri.Path()), err)
return
}
ctx.Hijack(func(conn net.Conn) {
defer dstConn.Close()
defer conn.Close()
errc := make(chan error, 2)
cp := func(dst io.Writer, src io.Reader) {
_, err := io.Copy(dst, src)
errc <- err
}
go cp(dstConn, conn)
go cp(conn, dstConn)
<-errc
})
}
示例4: SetPost
// SetPost is the API method for creating a new post.
func SetPost(ctx *fasthttp.RequestCtx, _ fasthttprouter.Params) {
v := &struct {
Title string
Body string
}{}
err := json.Unmarshal(ctx.PostBody(), v)
if err != nil {
ctx.Error(err.Error(), fasthttp.StatusInternalServerError)
return
}
p := model.NewPost(v.Title, v.Body)
id, err := p.Set(s)
if err != nil {
ctx.Error(err.Error(), fasthttp.StatusInternalServerError)
return
}
ctx.Response.Header.Set("Content-Type", "application/json")
resp, err := json.MarshalIndent(map[string]string{
"id": string(id),
}, "", " ")
if err != nil {
ctx.Error(err.Error(), fasthttp.StatusInternalServerError)
}
ctx.Write(resp)
}
示例5: TestRequest
func TestRequest(t *testing.T) {
ctx := new(fast.RequestCtx)
url, _ := url.Parse("http://github.com/labstack/echo")
ctx.Init(&fast.Request{}, fakeAddr{addr: "127.0.0.1"}, nil)
ctx.Request.Read(bufio.NewReader(bytes.NewBufferString(test.MultipartRequest)))
ctx.Request.SetRequestURI(url.String())
test.RequestTest(t, NewRequest(ctx, log.New("echo")))
}
示例6: NewRequest
// NewRequest returns `Request` instance.
func NewRequest(c *fasthttp.RequestCtx, l *log.Logger) *Request {
return &Request{
RequestCtx: c,
url: &URL{URI: c.URI()},
header: &RequestHeader{RequestHeader: &c.Request.Header},
logger: l,
}
}
示例7: ClientFormFastHandler
// ClientFormFastHandler 客户端表单信息(基于fasthttp)
func ClientFormFastHandler(ctx *fasthttp.RequestCtx) (clientID, clientSecret string, err error) {
clientID = string(ctx.FormValue("client_id"))
clientSecret = string(ctx.FormValue("client_secret"))
if clientID == "" || clientSecret == "" {
err = ErrAuthorizationFormInvalid
}
return
}
示例8: getQueriesCount
func getQueriesCount(ctx *fasthttp.RequestCtx) int {
n := ctx.QueryArgs().GetUintOrZero("queries")
if n < 1 {
n = 1
} else if n > 500 {
n = 500
}
return n
}
示例9: GetPostJSON
// GetPostJSON is the API method for getting a post's JSON.
func GetPostJSON(ctx *fasthttp.RequestCtx, ps fasthttprouter.Params) {
id := ps.ByName("id")
postJSON, err := model.GetJSON([]byte(id), s)
if err != nil {
ctx.Error(err.Error(), fasthttp.StatusNotFound)
return
}
ctx.Response.Header.Set("Content-Type", "application/json")
ctx.Write(postJSON)
}
示例10: CheckHost
// CheckHost Implement a CheckHost method on our new type
func (hs HostSwitch) CheckHost(ctx *fasthttp.RequestCtx) {
// Check if a http.Handler is registered for the given host.
// If yes, use it to handle the request.
if handler := hs[string(ctx.Host())]; handler != nil {
handler(ctx)
} else {
// Handle host names for wich no handler is registered
ctx.Error("Forbidden", 403) // Or Redirect?
}
}
示例11: getExpvarRegexp
func getExpvarRegexp(ctx *fasthttp.RequestCtx) (*regexp.Regexp, error) {
r := string(ctx.QueryArgs().Peek("r"))
if len(r) == 0 {
r = "."
}
rr, err := regexp.Compile(r)
if err != nil {
return nil, fmt.Errorf("cannot parse r=%q: %s", r, err)
}
return rr, nil
}
示例12: requestHandler
// Main request handler
func requestHandler(ctx *fasthttp.RequestCtx) {
path := ctx.Path()
switch {
case bytes.HasPrefix(path, imgPrefix):
imgHandler(ctx)
case bytes.HasPrefix(path, cssPrefix):
cssHandler(ctx)
default:
filesHandler(ctx)
}
}
示例13: TestExpvarHandlerRegexp
func TestExpvarHandlerRegexp(t *testing.T) {
var ctx fasthttp.RequestCtx
ctx.QueryArgs().Set("r", "cmd")
ExpvarHandler(&ctx)
body := string(ctx.Response.Body())
if !strings.Contains(body, `"cmdline"`) {
t.Fatalf("missing 'cmdline' expvar")
}
if strings.Contains(body, `"memstats"`) {
t.Fatalf("unexpected memstats expvar found")
}
}
示例14: ServeHTTP
// 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)
}
}
示例15: HandleTest
func HandleTest(ctx *fasthttp.RequestCtx) {
reader, err := os.Open("../testimages/loadimage/test.jpg")
if err != nil {
return
}
// Remember to free resources after you're done
defer reader.Close()
buffer := bytes.NewBuffer([]byte{})
buffer.ReadFrom(reader)
blob := buffer.Bytes()
ctx.Write(blob)
}