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) }
// ServeHTTP is called whenever there is a new request. // This is quite similar to JavaEE Servlet interface. func (h *MyHandler) ServeHTTP(ctx *fasthttp.RequestCtx) { // In the future we can use requester can detect request spammers! // requester := ctx.RemoteAddr() // Increase request count count := &(h.requests) atomic.AddUint64(count, 1) if ctx.IsGet() { url := ctx.URI() operations, format, err, invalid := ParseURI(url, h.imageSource, h.watermarker) if err != nil { ctx.NotFound() logging.Debug(err) return } if invalid != nil { ctx.Error(invalid.Error(), 400) return } blob, err := h.operator.GetBlob(operations...) if err != nil { ctx.NotFound() logging.Debug(err) } else { ctx.SetContentType("image/" + format) ctx.Write(blob) logging.Debug("Blob returned") } } else if ctx.IsPost() { // POST is currently unused so we can use this for testing h.RetrieveHello(ctx) logging.Debug("Post request received") } }
// 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) }
// 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) }
func fastHTTPHandler(ctx *fasthttp.RequestCtx) { if string(ctx.Method()) == "GET" { switch string(ctx.Path()) { case "/rest/hello": ctx.Write([]byte("Hello world")) default: ctx.Error("Unsupported path", fasthttp.StatusNotFound) } return } }
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())) } }
//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) }
// GetAllPosts is a method for getting every post func GetAllPosts(ctx *fasthttp.RequestCtx, _ fasthttprouter.Params) { posts, err := model.GetAll(s) if err != nil { ctx.Error(err.Error(), fasthttp.StatusNotFound) return } resp, err := json.MarshalIndent(posts, "", " ") if err != nil { ctx.Error(err.Error(), fasthttp.StatusInternalServerError) return } ctx.Response.Header.Set("Content-Type", "application/json") ctx.Write(resp) }
// /raw/msgs/:topic/:ver func (this *Gateway) pubRawHandler(ctx *fasthttp.RequestCtx, params fasthttprouter.Params) { var ( topic string ver string appid string pubkey string ) ver = params.ByName(UrlParamVersion) topic = params.ByName(UrlParamTopic) header := ctx.Request.Header appid = string(header.Peek(HttpHeaderAppid)) pubkey = string(header.Peek(HttpHeaderPubkey)) if err := manager.Default.OwnTopic(appid, pubkey, topic); err != nil { log.Error("app[%s] %s %+v: %v", appid, ctx.RemoteAddr(), params, err) ctx.SetConnectionClose() ctx.Error("invalid secret", fasthttp.StatusUnauthorized) return } cluster, found := manager.Default.LookupCluster(appid) if !found { log.Error("cluster not found for app: %s", appid) ctx.Error("invalid appid", fasthttp.StatusBadRequest) return } var out = map[string]string{ "store": "kafka", "broker.list": strings.Join(meta.Default.BrokerList(cluster), ","), "topic": manager.Default.KafkaTopic(appid, topic, ver), } b, _ := json.Marshal(out) ctx.SetContentType("application/json; charset=utf8") ctx.Write(b) }
func (a *API) Handler(ctx *fasthttp.RequestCtx) { ctx.SetContentType("application/json") ctx.Response.Header.Set("Access-Control-Allow-Origin", "*") switch string(ctx.Path()) { case "/rules": j, err := json.Marshal(a.Proxy.Rules) if err != nil { ctx.Error(fmt.Sprintf("{\"error\": \"%v\"}", err), 500) return } ctx.Write(j) case "/rules/reload": if err := a.Proxy.ReloadRules(a.RuleFile); err != nil { ctx.Error(fmt.Sprintf("{\"error\": \"%v\"}", err), 500) return } log.Println("Rule file reloaded") ctx.Write([]byte("{\"status\": \"ok\"}")) default: ctx.Error("{\"error\": \"Not found\"}", fasthttp.StatusNotFound) } }
// 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 }
// Test 6: Plaintext func plaintextHandler(ctx *fasthttp.RequestCtx) { ctx.Write(helloWorldBytes) }
//fasthttprouter func fastHttpHandler(ctx *fasthttp.RequestCtx, ps fasthttprouter.Params) { if sleepTime > 0 { time.Sleep(sleepTimeDuration) } ctx.Write(message) }
func (b *blockAction) Act(_ string, ctx *fasthttp.RequestCtx) error { ctx.SetStatusCode(429) ctx.Write(b.message) return nil }
func hello(ctx *fasthttp.RequestCtx) { ctx.SetContentType("text/plain; charset=utf8") ctx.Write([]byte("hello world")) }
// /topics/:topic/:ver?key=mykey&async=1&delay=100 func (this *Gateway) pubHandler(ctx *fasthttp.RequestCtx, params fasthttprouter.Params) { t1 := time.Now() topic := params.ByName(UrlParamTopic) header := ctx.Request.Header appid := string(header.Peek(HttpHeaderAppid)) pubkey := string(header.Peek(HttpHeaderPubkey)) if err := manager.Default.OwnTopic(appid, pubkey, topic); err != nil { log.Error("app[%s] %s %+v: %v", appid, ctx.RemoteAddr(), params, err) ctx.SetConnectionClose() ctx.Error("invalid secret", fasthttp.StatusUnauthorized) return } msgLen := ctx.Request.Header.ContentLength() switch { case msgLen == -1: log.Warn("pub[%s] %s %+v invalid content length", appid, ctx.RemoteAddr(), params) ctx.Error("invalid content length", fasthttp.StatusBadRequest) return case int64(msgLen) > options.MaxPubSize: log.Warn("pub[%s] %s %+v too big content length:%d", appid, ctx.RemoteAddr(), params, msgLen) ctx.Error(ErrTooBigPubMessage.Error(), fasthttp.StatusBadRequest) return case msgLen < options.MinPubSize: log.Warn("pub[%s] %s %+v too small content length:%d", appid, ctx.RemoteAddr(), params, msgLen) ctx.Error(ErrTooSmallPubMessage.Error(), fasthttp.StatusBadRequest) return } ver := params.ByName(UrlParamVersion) queryArgs := ctx.Request.URI().QueryArgs() key := queryArgs.Peek("key") asyncArg := queryArgs.Peek("async") async := len(asyncArg) == 1 && asyncArg[0] == '1' //delay := hack.String(queryArgs.Peek("delay")) if options.Debug { log.Debug("pub[%s] %s {topic:%s, ver:%s, key:%s, async:%+v} %s", appid, ctx.RemoteAddr(), topic, ver, key, async, string(ctx.Request.Body())) } if !options.DisableMetrics { this.pubMetrics.PubQps.Mark(1) this.pubMetrics.PubMsgSize.Update(int64(len(ctx.PostBody()))) } pubMethod := store.DefaultPubStore.SyncPub if async { pubMethod = store.DefaultPubStore.AsyncPub } cluster, found := manager.Default.LookupCluster(appid) if !found { log.Error("cluster not found for app: %s", appid) ctx.Error("invalid appid", fasthttp.StatusBadRequest) return } err := pubMethod(cluster, manager.Default.KafkaTopic(appid, topic, ver), key, ctx.PostBody()) if err != nil { if !options.DisableMetrics { this.pubMetrics.PubFail(appid, topic, ver) } log.Error("%s: %v", ctx.RemoteAddr(), err) ctx.Error(err.Error(), fasthttp.StatusInternalServerError) return } // write the reponse ctx.Write(ResponseOk) if !options.DisableMetrics { this.pubMetrics.PubOk(appid, topic, ver) this.pubMetrics.PubLatency.Update(time.Since(t1).Nanoseconds() / 1e6) // in ms } }
func (this *Gateway) pubCheckHandler(ctx *fasthttp.RequestCtx, params fasthttprouter.Params) { ctx.Write(ResponseOk) }