func httpTimeline(c *echo.Context) error { r := c.Request() w := c.Response() e := c.Get("engine").(storage.Engine) domain := c.Param("domain") iter, code, err := domainIteratorResource(domain, r, e) if err != nil { return c.JSON(code, map[string]interface{}{ "error": fmt.Sprint(err), }) } events, err := view.Timeline(iter, view.Descending) if err != nil { return c.JSON(code, map[string]interface{}{ "error": fmt.Sprint(err), }) } return json.NewEncoder(w).Encode(events) }
func CustomHTTPErrorHandler(err error, c echo.Context) { code := http.StatusInternalServerError response := ErrResponse{} switch v := err.(type) { case types.ErrNotFound: code = http.StatusNotFound response = ErrResponse{"error": v.Error()} case types.ErrConflict: code = http.StatusConflict response = ErrResponse{"error": v.Error()} case types.ErrValidation: code = http.StatusUnprocessableEntity response = ErrResponse{"error": v.Errors} case *echo.HTTPError: response = ErrResponse{"error": v.Message} default: response = ErrResponse{"error": v.Error()} } if !c.Response().Committed { if c.Request().Method == echo.HEAD { // Issue #608 c.NoContent(code) } else { c.JSON(code, response) } } }
// DeleteSession delete session by name. func DeleteSession(ctx *echo.Context, sessionName string) error { ss, err := store.Get(ctx.Request(), sessionName) if err != nil { return err } return store.Delete(ctx.Request(), ctx.Response(), ss) }
func apiHandler(c *echo.Context) error { i := 0 response := c.Response() // ustawiamy header na event-stream rozpoznawalny przez przeglądarkę response.Header().Set(echo.ContentType, "text/event-stream") response.WriteHeader(http.StatusOK) // 200 for { location := locations[i] response.Write([]byte("data: ")) if err := json.NewEncoder(response).Encode(location); err != nil { return err } response.Write([]byte("\n\n")) response.Flush() time.Sleep(100 * time.Millisecond) i++ if i >= len(locations) { i = 0 } } return nil }
func httpLog(c *echo.Context) error { r := c.Request() w := c.Response() e := c.Get("engine").(storage.Engine) domain := c.Param("domain") iter, code, err := domainIteratorResource(domain, r, e) if err != nil { return c.JSON(code, map[string]interface{}{ "error": fmt.Sprint(err), }) } facts, err := origins.ReadAll(iter) if err != nil { return c.JSON(code, map[string]interface{}{ "error": fmt.Sprint(err), }) } return json.NewEncoder(w).Encode(facts) }
func (rc *ResourceController) IndexHandler(c *echo.Context) error { defer func() error { if r := recover(); r != nil { switch x := r.(type) { case search.Error: return c.JSON(x.HTTPStatus, x.OperationOutcome) default: outcome := models.NewOperationOutcome("fatal", "exception", "") return c.JSON(http.StatusInternalServerError, outcome) } } return nil }() searchQuery := search.Query{Resource: rc.Name, Query: c.Request().URL.RawQuery} baseURL := responseURL(c.Request(), rc.Name) bundle, err := rc.DAL.Search(*baseURL, searchQuery) if err != nil { return err } c.Set("bundle", bundle) c.Set("Resource", rc.Name) c.Set("Action", "search") c.Response().Header().Set("Access-Control-Allow-Origin", "*") return c.JSON(http.StatusOK, bundle) }
func (s *APIServer) getFeeds(c echo.Context) error { dbuser := c.Get("dbuser").(*db.User) b := new(feedsReqBinder) if err := c.Bind(b); err != nil { return newError(c, "Unable to parse request", err) } var feeds []*db.FeedInfo var err error if b.Name != "" { feeds, err = s.DBH.GetUsersFeedsByName(dbuser, b.Name) } else { feeds, err = s.DBH.GetUsersFeeds(dbuser) } if err != nil { return newError(c, "Unable to get feeds", err) } feedInterface := make([]interface{}, len(feeds)) for i, f := range feeds { feedInterface[i] = f } c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8) c.Response().WriteHeader(http.StatusOK) return jsonapi.MarshalManyPayload(c.Response(), feedInterface) }
func success(ctx echo.Context, data interface{}) error { result := map[string]interface{}{ "ok": 1, "msg": "操作成功", "data": data, } b, err := json.Marshal(result) if err != nil { return err } go func(b []byte) { if cacheKey := ctx.Get(nosql.CacheKey); cacheKey != nil { nosql.DefaultLRUCache.CompressAndAdd(cacheKey, b, nosql.NewCacheData()) } }(b) if ctx.Response().Committed() { getLogger(ctx).Flush() return nil } return ctx.JSONBlob(http.StatusOK, b) }
// echov2-standard func echov2Handler(c echov2.Context) error { if sleepTime > 0 { time.Sleep(sleepTimeDuration) } c.Response().Write(message) return nil }
func (h *handler) handleDownloadTarFunc(c echo.Context) error { pathToSend := c.QueryParam("path") fileFilter := c.QueryParam("file-filter") if strings.TrimSpace(pathToSend) == "" { return fmt.Errorf("Request does not contain query 'path' value") } var tarProvider tar_io.TarProvider if isDir, err := path_utils.DirectoryExists(pathToSend); err != nil { return fmt.Errorf("Unable to determine if path '%s' is a directory, error: %s", pathToSend, err.Error()) } else if isDir { tarProvider = tar_io.Factories.TarProvider.Dir(pathToSend, fileFilter) h.logger.Infof("Now starting to send dir '%s'", pathToSend) } else if isFile, err := path_utils.FileExists(pathToSend); err != nil { return fmt.Errorf("Unable to determine if path '%s' is a file, error: %s", pathToSend, err.Error()) } else if isFile { tarProvider = tar_io.Factories.TarProvider.File(pathToSend) h.logger.Infof("Now starting to send file '%s'", pathToSend) } else { return fmt.Errorf("Path '%s' is not an existing file or directory", pathToSend) } handler := &sendTarHandler{writer: c.Response()} err := tar_io.UploadProvider(tarProvider, handler) if err != nil { return fmt.Errorf("Unable to send file, error: %s", err.Error()) } return nil }
// FileServerHandler function func FileServerHandler(c *echo.Context) error { fileType := mime.TypeByExtension(filepath.Ext(filepath.Base(c.Request().URL.String()))) log.Println(c.Request().URL.String()[1:]) c.Response().Header().Set("Content-Type", fileType) io.Copy(c.Response(), bytes.NewReader(staticFiles.Get(c.Request().URL.String()[1:]))) return nil }
func Index(c *echo.Context) error { authCookie, err := c.Request().Cookie("testcook") logrus.Infof(">>> cooki: %+v, err: %+v", authCookie, err) dbconn := c.Get("db").(*mgo.Database) counts := dbconn.C("counts") if err := counts.Insert(&models.TestStruct{"index"}); err != nil { c.String(500, fmt.Sprintf("broken: %s", err.Error())) return nil } t, err := template.ParseFiles("static/html/layout.html", "static/html/greet.html", "static/html/mainPage.html") if err != nil { c.String(500, fmt.Sprintf("broken: %s", err.Error())) return nil } loggedIn := false user, ok := c.Get("user").(models.Account) if ok { loggedIn = user.Username != "" } args := map[string]interface{}{ "Username": user.Username, "LoggedIn": loggedIn, "Logout": fmt.Sprintf("http://*****:*****@%s", viper.GetString("base_uri"))} t.Execute(c.Response(), args) return nil }
func getVersion(ctx *echo.Context) error { ctx.Response().Header().Set(echo.ContentType, echo.ApplicationJSON) return ctx.JSON(http.StatusOK, VersionInfo{ Name: APP_NAME, Version: APP_VERSION, Author: APP_AUTHOR, }) }
// 将结果写入到http请求(ProtoBuffer 格式) func SendProto(c echo.Context, code int, data proto.Message) error { resp := c.Response() err := utils.SendFrame(resp, data) if err != nil { return err } resp.WriteHeader(code) return nil }
func sendJSONResponse(toMarshal interface{}, c echo.Context) error { b, err := json.Marshal(toMarshal) if err != nil { return err } c.Response().Write(b) return nil }
// LoginPost handlers login form, and logs in the user. If the form is valid, the user is // redirected to "/auth/login" with the form validation errors. When the user is validated // redirection is made to "/". // // Method POST // // Route /auth/login // // Restrictions None // // Template None (All actions redirect to other routes ) // // Flash messages may be set before redirection. func LoginPost(ctx *echo.Context) error { var flashMessages = flash.New() f := forms.New(utils.GetLang(ctx)) lf := f.LoginForm()(ctx.Request()) if !lf.IsValid() { utils.SetData(ctx, authForm, lf) ctx.Redirect(http.StatusFound, "/auth/login") return nil } // Check email and password user, err := query.AuthenticateUserByEmail(lf.GetModel().(forms.Login)) if err != nil { log.Error(ctx, err) // We want the user to try again, but rather than rendering the form right // away, we redirect him/her to /auth/login route(where the login process with // start aflsesh albeit with a flash message) flashMessages.Err(msgLoginErr) flashMessages.Save(ctx) ctx.Redirect(http.StatusFound, "/auth/login") return nil } // create a session for the user after the validation has passed. The info stored // in the session is the user ID, where as the key is userID. ss, err := sessStore.Get(ctx.Request(), settings.App.Session.Name) if err != nil { log.Error(ctx, err) } ss.Values["userID"] = user.ID err = ss.Save(ctx.Request(), ctx.Response()) if err != nil { log.Error(ctx, err) } person, err := query.GetPersonByUserID(user.ID) if err != nil { log.Error(ctx, err) flashMessages.Err(msgLoginErr) flashMessages.Save(ctx) ctx.Redirect(http.StatusFound, "/auth/login") return nil } // add context data. IsLoged is just a conveniece in template rendering. the User // contains a models.Person object, where the PersonName is already loaded. utils.SetData(ctx, "IsLoged", true) utils.SetData(ctx, "User", person) flashMessages.Success(msgLoginSuccess) flashMessages.Save(ctx) ctx.Redirect(http.StatusFound, "/") log.Info(ctx, "login success") return nil }
func (a *Application) logout(c *echo.Context) error { loginCookie, err := c.Request().Cookie("login") if err != nil { fmt.Println(err) } else { a.Redis.RemoveSession(loginCookie.Value) http.SetCookie(c.Response(), &http.Cookie{Name: "login", MaxAge: -1}) } return c.Redirect(302, "/") }
// 将结果写入到http请求(Json 格式) func SendJson(c echo.Context, code int, data proto.Message) error { resp := c.Response() buffer, err := json.Marshal(data) if err != nil { return err } resp.Write(buffer) resp.WriteHeader(code) resp.Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8) return nil }
func (s *yovpnServer) createEndpoint(c *echo.Context) error { region := c.Query("region") if len(region) == 0 { return echo.NewHTTPError(http.StatusBadRequest, "You need to provide a region!") } endpoint := s.provisioner.CreateEndpoint(region) c.Response().Header().Set(echo.Location, c.Echo().URI(s.getEndpoint, endpoint.ID)) c.JSON(http.StatusAccepted, endpoint) return nil }
func (h *handler) NotFoundHandler(err error, c *echo.Context) { if he, ok := err.(*echo.HTTPError); ok { if he.Code() == http.StatusNotFound { http.Error(c.Response(), "Error 404. Page not found", http.StatusNotFound) return } } return }
func (h *handler) OauthCallbackHandler(c *echo.Context) error { code := c.Query("code") token, err := oauthConf.Exchange(oauth2.NoContext, code) if err != nil { log.Println(err.Error(), "Can't exchange token") return c.Redirect(http.StatusTemporaryRedirect, "/") } oauthClient := oauthConf.Client(oauth2.NoContext, token) client := github.NewClient(oauthClient) user, _, err := client.Users.Get("") if err != nil { log.Println(err.Error(), "Can't get user") return c.Redirect(http.StatusTemporaryRedirect, "/") } userLogin := *user.Login userToken := token.AccessToken u := &model.UserRow{ Login: userLogin, Token: userToken, AvatarURL: *user.AvatarURL, } ci, err := h.back.Model.User.CreateOrUpdate(u) if err != nil { log.Println(err.Error(), "Can't create user") return c.Redirect(http.StatusTemporaryRedirect, "/") } s := session.Default(c) if ci.Updated == 0 { s.Set("just_signup", true) } else { u, err = h.back.Model.User.GetByLogin(userLogin) if err != nil { return c.Redirect(http.StatusTemporaryRedirect, "/") } } var buf bytes.Buffer enc := json.NewEncoder(&buf) enc.Encode(*u) s.Set("username", userLogin) s.Set("user", buf.String()) // hack to display username in header http.SetCookie(c.Response(), &http.Cookie{Name: "username", Value: userLogin, Path: "/"}) http.SetCookie(c.Response(), &http.Cookie{Name: "useravatar", Value: *user.AvatarURL, Path: "/"}) s.Set("token", userToken) s.Save() return c.Redirect(http.StatusFound, "/dashboard") }
func CrossDomain(c *echo.Context) error { c.Response().Header().Set("Access-Control-Allow-Origin", "*") c.Request().Header.Set("Access-Control-Allow-Credentials", "true") c.Request().Header.Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") c.Request().Header.Set("Access-Control-Allow-Headers", "Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, X-Requested-By, If-Modified-Since, X-File-Name, Cache-Control, X-XSRFToken, Authorization") c.Request().Header.Set("Content-Type", "application/json") if c.Request().Method == "OPTIONS" { c.String(204, "") } return nil }
// proxy and cache images from imdb func (app *App) proxyImg(c *echo.Context) error { resp := retriveFromCache(c.Param("_*")) data, _ := ioutil.ReadAll(resp.Body) for k, v := range resp.Header { if len(v) > 0 { c.Response().Header().Add(k, v[0]) } } c.Response().Write(data) return nil }
func oauthError(c *echo.Context, fail *oauth2.OAuthError) error { b, err := fail.ToJSON() if err != nil { return err } w := c.Response() w.WriteHeader(fail.HTTPStatusCode) w.Header().Set("Content-Type", "application/json") w.Write(b) return nil }
func (rc *ResourceController) ShowHandler(c *echo.Context) error { c.Set("Action", "read") _, err := rc.LoadResource(c) if err != nil && err != ErrNotFound { return err } c.Response().Header().Set("Access-Control-Allow-Origin", "*") if err == ErrNotFound { return c.NoContent(http.StatusNotFound) } return c.JSON(http.StatusOK, c.Get(rc.Name)) }
func (rc *ResourceController) ConditionalDeleteHandler(c *echo.Context) error { query := search.Query{Resource: rc.Name, Query: c.Request().URL.RawQuery} _, err := rc.DAL.ConditionalDelete(query) if err != nil { return err } c.Set("Resource", rc.Name) c.Set("Action", "delete") c.Response().Header().Set("Access-Control-Allow-Origin", "*") return c.NoContent(http.StatusNoContent) }
func Upload(c *echo.Context) error { initProcess(c.Request()) if data, err := process.Encode(c.Response(), c.Request(), sprocess.GenId()); err != nil { log.Fatal(err) return err } else { str, ok := data["medialink"].(string) if !ok { /* act on str */ } return c.String(http.StatusOK, str) } }
func (as ApiService) addService(c echo.Context) error { var newService types.Service if err := c.Bind(&newService); err != nil { return err } if err := as.balancer.AddService(&newService); err != nil { return err } c.Response().Header().Add("Location", "/services/"+newService.Name) return c.JSON(http.StatusCreated, newService) }
func JSONHTTPErrorHandler(err error, c echo.Context) { code := fasthttp.StatusInternalServerError msg := "Internal Server Error" if he, ok := err.(*echo.HTTPError); ok { code = he.Code msg = he.Message } if !c.Response().Committed() { c.JSON(code, map[string]interface{}{ "statusCode": code, "message": msg, }) } }
func (rc *ResourceController) DeleteHandler(c *echo.Context) error { id := c.Param("id") if err := rc.DAL.Delete(id, rc.Name); err != nil && err != ErrNotFound { return err } c.Set(rc.Name, id) c.Set("Resource", rc.Name) c.Set("Action", "delete") c.Response().Header().Set("Access-Control-Allow-Origin", "*") return c.NoContent(http.StatusNoContent) }