本文整理汇总了Golang中github.com/valyala/fasthttp.RequestCtx类的典型用法代码示例。如果您正苦于以下问题:Golang RequestCtx类的具体用法?Golang RequestCtx怎么用?Golang RequestCtx使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了RequestCtx类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
}
开发者ID:stellar,项目名称:bridge-server,代码行数:27,代码来源:binder.go
示例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")
}
开发者ID:valyala,项目名称:fasthttp,代码行数:33,代码来源:expvar.go
示例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
})
}
开发者ID:txrxio,项目名称:planb,代码行数:33,代码来源:fasthttp.go
示例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)
}
开发者ID:bentranter,项目名称:lazyblog,代码行数:26,代码来源:handler.go
示例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")))
}
开发者ID:ZloyDyadka,项目名称:echo,代码行数:8,代码来源:request_test.go
示例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,
}
}
开发者ID:efimovalex,项目名称:EventKitAPI,代码行数:9,代码来源:request.go
示例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
}
开发者ID:Curtis-ly,项目名称:oauth2,代码行数:9,代码来源:authorize.go
示例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
}
开发者ID:tussion,项目名称:FrameworkBenchmarks,代码行数:9,代码来源:hello.go
示例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)
}
开发者ID:bentranter,项目名称:lazyblog,代码行数:11,代码来源:handler.go
示例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?
}
}
开发者ID:Taik,项目名称:zing-mp3,代码行数:11,代码来源:hosts.go
示例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
}
开发者ID:valyala,项目名称:fasthttp,代码行数:11,代码来源:expvar.go
示例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)
}
}
开发者ID:ty2,项目名称:fasthttp,代码行数:12,代码来源:fs_handler_example_test.go
示例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")
}
}
开发者ID:stellar,项目名称:bridge-server,代码行数:12,代码来源:expvar_test.go
示例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)
}
}
开发者ID:tpbowden,项目名称:swarm-ingress-router,代码行数:14,代码来源:proxy_handler.go
示例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)
}
开发者ID:phzfi,项目名称:RIC,代码行数:14,代码来源:loadimageweb_test.go
示例16: TestServerWrapHandler
func TestServerWrapHandler(t *testing.T) {
e := echo.New()
ctx := new(fasthttp.RequestCtx)
req := NewRequest(ctx, nil)
res := NewResponse(ctx, nil)
c := e.NewContext(req, res)
h := WrapHandler(func(ctx *fasthttp.RequestCtx) {
ctx.Write([]byte("test"))
})
if assert.NoError(t, h(c)) {
assert.Equal(t, http.StatusOK, ctx.Response.StatusCode())
assert.Equal(t, "test", string(ctx.Response.Body()))
}
}
开发者ID:o1egl,项目名称:echo,代码行数:14,代码来源:server_test.go
示例17: mainHandler
func mainHandler(ctx *fasthttp.RequestCtx) {
// Performance hack for prefork mode - periodically close keepalive
// connections for evenly distributing connections among available
// processes.
if *prefork {
maxDuration := maxConnDuration + time.Millisecond*time.Duration(atomic.LoadUint64(&connDurationJitter))
if time.Since(ctx.ConnTime()) > maxDuration {
atomic.StoreUint64(&connDurationJitter, uint64(rand.Intn(100)))
ctx.SetConnectionClose()
}
}
path := ctx.Path()
switch string(path) {
case "/plaintext":
plaintextHandler(ctx)
case "/json":
jsonHandler(ctx)
case "/db":
dbHandler(ctx)
case "/queries":
queriesHandler(ctx)
case "/fortune":
fortuneHandler(ctx)
case "/update":
updateHandler(ctx)
default:
ctx.Error("unexpected path", fasthttp.StatusBadRequest)
}
}
开发者ID:tussion,项目名称:FrameworkBenchmarks,代码行数:30,代码来源:hello.go
示例18: responseStreamHandler
func responseStreamHandler(ctx *fasthttp.RequestCtx) {
// Send the response in chunks and wait for a second between each chunk.
ctx.SetBodyStreamWriter(func(w *bufio.Writer) {
for i := 0; i < 10; i++ {
fmt.Fprintf(w, "this is a message number %d", i)
// Do not forget flushing streamed data to the client.
if err := w.Flush(); err != nil {
return
}
time.Sleep(time.Second)
}
})
}
开发者ID:stellar,项目名称:bridge-server,代码行数:14,代码来源:requestctx_setbodystreamwriter_example_test.go
示例19: fastHttpRawHandler
//fasthttp
func fastHttpRawHandler(ctx *fasthttp.RequestCtx) {
if string(ctx.Method()) == "GET" {
switch string(ctx.Path()) {
case "/hello":
if sleepTime > 0 {
time.Sleep(sleepTimeDuration)
}
ctx.Write(message)
default:
ctx.Error("Unsupported path", fasthttp.StatusNotFound)
}
return
}
ctx.Error("Unsupported method", fasthttp.StatusMethodNotAllowed)
}
开发者ID:cokeboL,项目名称:go-web-framework-benchmark,代码行数:16,代码来源:server.go
示例20: Serve
func (g *Goka) Serve(rCtx *fasthttp.RequestCtx) {
c := g.pool.Get().(*Context)
h, g := g.router.Find(string(rCtx.Method()), string(rCtx.Path()), c)
c.reset(rCtx, g)
for i := len(g.middleware) - 1; i >= 0; i-- {
h = g.middleware[i](h)
}
if err := h(c); err != nil {
g.httpErrorHandler(err, c)
}
g.pool.Put(c)
}
开发者ID:gotokatsuya,项目名称:goka,代码行数:16,代码来源:goka.go
注:本文中的github.com/valyala/fasthttp.RequestCtx类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论