本文整理汇总了Golang中github.com/labstack/echo.Context.Request方法的典型用法代码示例。如果您正苦于以下问题:Golang Context.Request方法的具体用法?Golang Context.Request怎么用?Golang Context.Request使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/labstack/echo.Context
的用法示例。
在下文中一共展示了Context.Request方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: NewQuote
//POST /quotes
//POST /slack/insertQuote
func (a *AppContext) NewQuote(c *echo.Context) error {
r := c.Request()
SetDefaultHeaders(c)
//Parse post values
r.ParseForm()
isValid := len(r.Form["text"]) > 0 && len(r.Form["team_id"]) > 0
if !isValid {
log.Println("Invalid form (empty?)\nI'm a doctor Jim, not a magician!")
return c.JSON(http.StatusBadRequest, "Looks like I'm missing some parameters, sir.")
}
fmt.Printf("form:: %s\n", r.Form)
//Transfer post values to quote variable
quote := new(st.Quote)
decoder := schema.NewDecoder()
if err := decoder.Decode(quote, c.Request().PostForm); err != nil {
fmt.Println(err)
}
fmt.Printf("Filled quote: %#v\n", quote)
//Save the quote in the database
a.Storage.SaveQuote(quote)
resp := "Saving quote: " + quote.Text
fmt.Println("\n\n")
return c.JSON(http.StatusOK, resp)
}
示例2: GetHabloAuth
// GetHabloAuth returns an hablo authorization if available and valid
func GetHabloAuth(c *echo.Context) (*models.HabloAuth, error) {
header := c.Request().Header
authv := header.Get("Authorization")
// Get bearer token
if !strings.HasPrefix(strings.ToLower(authv), "bearer") {
return nil, ErrNoToken
}
values := strings.Split(authv, " ")
if len(values) < 2 {
return nil, ErrNoToken
}
token := values[1]
// Find token in collection
var auth models.HabloAuth
err := mangos.FindOne(models.NCAuth, bson.M{"token": token}, &auth)
if err != nil {
return nil, err
}
return &auth, nil
}
示例3: CustomHTTPErrorHandler
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)
}
}
}
示例4: DeleteSession
// 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)
}
示例5: upload
func upload(c *echo.Context) error {
req := c.Request()
req.ParseMultipartForm(16 << 20) // Max memory 16 MiB
// Read form fields
name := c.Form("name")
email := c.Form("email")
// Read files
files := req.MultipartForm.File["files"]
for _, f := range files {
// Source file
src, err := f.Open()
if err != nil {
return err
}
defer src.Close()
// Destination file
dst, err := os.Create(f.Filename)
if err != nil {
return err
}
defer dst.Close()
if _, err = io.Copy(dst, src); err != nil {
return err
}
}
return c.String(http.StatusOK, "Thank You! %s <%s>, %d files uploaded successfully.",
name, email, len(files))
}
示例6: putValues
func (app *App) putValues(ctx *echo.Context) (err error) {
key := ctx.Param("key")
value, err := readBody(ctx.Request())
if err != nil {
return err
}
app.Lock()
entry, ok := app.store[key]
if !ok {
entry = newEntry()
entry.Lock()
app.store[key] = entry
} else {
entry.Lock()
}
app.Unlock()
entry.value = value
entry.lockID = generateID(32)
app.cond.Broadcast()
entry.Unlock()
response := map[string]interface{}{}
response["lock_id"] = entry.lockID
ctx.JSON(200, response)
return
}
示例7: Create
// Create 发布新资源
func (ResourceController) Create(ctx echo.Context) error {
title := ctx.FormValue("title")
// 请求新建资源页面
if title == "" || ctx.Request().Method() != "POST" {
return render(ctx, "resources/new.html", map[string]interface{}{"activeResources": "active", "categories": logic.AllCategory})
}
errMsg := ""
resForm := ctx.FormValue("form")
if resForm == model.LinkForm {
if ctx.FormValue("url") == "" {
errMsg = "url不能为空"
}
} else {
if ctx.FormValue("content") == "" {
errMsg = "内容不能为空"
}
}
if errMsg != "" {
return fail(ctx, 1, errMsg)
}
me := ctx.Get("user").(*model.Me)
err := logic.DefaultResource.Publish(ctx, me, ctx.FormParams())
if err != nil {
return fail(ctx, 2, "内部服务错误,请稍候再试!")
}
return success(ctx, nil)
}
示例8: Modify
// Modify 修改主题
func (TopicController) Modify(ctx echo.Context) error {
tid := goutils.MustInt(ctx.FormValue("tid"))
if tid == 0 {
return ctx.Redirect(http.StatusSeeOther, "/topics")
}
nodes := logic.GenNodes()
if ctx.Request().Method() != "POST" {
topics := logic.DefaultTopic.FindByTids([]int{tid})
if len(topics) == 0 {
return ctx.Redirect(http.StatusSeeOther, "/topics")
}
return render(ctx, "topics/new.html", map[string]interface{}{"nodes": nodes, "topic": topics[0], "activeTopics": "active"})
}
me := ctx.Get("user").(*model.Me)
err := logic.DefaultTopic.Publish(ctx, me, ctx.FormParams())
if err != nil {
if err == logic.NotModifyAuthorityErr {
return fail(ctx, 1, "没有权限操作")
}
return fail(ctx, 2, "服务错误,请稍后重试!")
}
return success(ctx, nil)
}
示例9: OverrideRequestMethod
// OverrideRequestMethod overrides the http
// request's method with the specified method.
func OverrideRequestMethod(c *echo.Context, method string) error {
if !isValidOverrideMethod(method) {
return ErrInvalidOverrideMethod
}
c.Request().Header.Set(HeaderHTTPMethodOverride, method)
return nil
}
示例10: GetActivities
//GET /activities
func (a *AppContext) GetActivities(c *echo.Context) error {
var activities []st.Activity
var err error
var query = c.Request().URL.Query().Get("q")
//Check for token header
SetDefaultHeaders(c)
//Get quote from database
if query != "" {
//Seperate search terms and put them into a string array
activities, err = a.Storage.SearchActivities(strings.Split(query, ","))
} else {
activities, err = a.Storage.FindAllActivities()
}
if err != nil {
return c.JSON(http.StatusBadRequest, Error{"Activities could not be found.", err})
}
return c.JSON(http.StatusOK, FormatResponse("Fetched", activities))
}
示例11: EmailUnsub
// EmailUnsub 邮件订阅/退订页面
func (UserController) EmailUnsub(ctx echo.Context) error {
token := ctx.FormValue("u")
if token == "" {
return ctx.Redirect(http.StatusSeeOther, "/")
}
// 校验 token 的合法性
email := ctx.FormValue("email")
user := logic.DefaultUser.FindOne(ctx, "email", email)
if user.Email == "" {
return ctx.Redirect(http.StatusSeeOther, "/")
}
realToken := logic.DefaultEmail.GenUnsubscribeToken(user)
if token != realToken {
return ctx.Redirect(http.StatusSeeOther, "/")
}
if ctx.Request().Method() != "POST" {
data := map[string]interface{}{
"email": email,
"token": token,
"unsubscribe": user.Unsubscribe,
}
return render(ctx, "user/email_unsub.html", data)
}
logic.DefaultUser.EmailSubscribe(ctx, user.Uid, goutils.MustInt(ctx.FormValue("unsubscribe")))
return success(ctx, nil)
}
示例12: checkRateLimit
// Checking rate limit 10 request / 1 sec.
func checkRateLimit(con redis.Conn, c *echo.Context) bool {
ip, _, err := net.SplitHostPort(c.Request().RemoteAddr)
if err != nil {
panic(err)
}
//If list of ip address's length is 10 retun false.
current, err := redis.Int(con.Do("LLEN", ip))
if err == nil && current > 10 {
return false
}
exists, err := redis.Bool(con.Do("EXISTS", ip))
if err != nil {
panic(err)
}
if !exists {
con.Send("MULTI")
con.Send("RPUSH", ip, ip)
con.Send("EXPIRE", ip, 1)
_, err := con.Do("EXEC")
if err != nil {
panic(err)
}
} else {
_, err := con.Do("RPUSHX", ip, ip)
if err != nil {
panic(err)
}
}
return true
}
示例13: RegisterPost
// RegisterPost handles registration form, and create a session for the new user if the registration
// process is complete.
//
// Method POST
//
// Route /auth/register
//
// Restrictions None
//
// Template None (All actions redirect to other routes )
//
// Flash messages may be set before redirection.
func RegisterPost(ctx *echo.Context) error {
var flashMessages = flash.New()
f := forms.New(utils.GetLang(ctx))
lf := f.RegisterForm()(ctx.Request())
if !lf.IsValid() {
// Case the form is not valid, ships it back with the errors exclusively
utils.SetData(ctx, authForm, lf)
return ctx.Render(http.StatusOK, tmpl.RegisterTpl, utils.GetData(ctx))
}
// we are not interested in the returned user, rather we make sure the user has
// been created.
_, err := query.CreateNewUser(lf.GetModel().(forms.Register))
if err != nil {
flashMessages.Err(msgAccountCreateFailed)
flashMessages.Save(ctx)
ctx.Redirect(http.StatusFound, "/auth/register")
return nil
}
// TODO: improve the message to include directions to use the current email and
// password to login?
flashMessages.Success(msgAccountCreate)
flashMessages.Save(ctx)
// Don't create session in this route, its best to leave only one place which
// messes with the main user session. So we redirect to the login page, and encourage
// the user to login.
ctx.Redirect(http.StatusFound, "/auth/login")
return nil
}
示例14: Index
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://username:[email protected]%s", viper.GetString("base_uri"))}
t.Execute(c.Response(), args)
return nil
}
示例15: httpTimeline
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)
}