登录
首页 >  Golang >  Go问答

如何实现在新贴网址中进行重定向以显示布法罗的贴文

来源:stackoverflow

时间:2024-03-15 16:24:29 442浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《如何实现在新贴网址中进行重定向以显示布法罗的贴文》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

问题内容

我正在布法罗建立一个博客网站,但遇到了一些问题。我在 app.go 中有以下路线:

b := blogsresource{}
bloggroup := app.group("/blog")
bloggroup.get("/", b.list)
bloggroup.get("/new", b.new)
bloggroup.get("/post/{slug}", b.show)
bloggroup.get("/post/{slug}/edit", b.edit)
bloggroup.post("/", b.create)
bloggroup.put("/post/{slug}", b.update)
bloggroup.delete("/post/{slug}", b.destroy)
bloggroup.middleware.skip(authorize, b.list, b.show)

我的 blogs.go 资源创建方法如下所示:

func (v blogsresource) create(c buffalo.context) error {
    // allocate an empty blog
    blog := &models.blog{}

    // bind blog to the html form elements
    if err := c.bind(blog); err != nil {
        return errors.withstack(err)
    }

    // get the db connection from the context and validate it
    tx := c.value("tx").(*pop.connection)
    verrs, err := blog.create(tx)

    if err != nil {
        return errors.withstack(err)
    }

    if verrs.hasany() {
        // make the errors available inside the html template
        c.set("errors", verrs)

        // render again the new.html template that the user can
        // correct the input.
        return c.render(422, r.auto(c, blog))
    }

    // if there are no errors set a success message
    c.flash().add("success", t.translate(c, "blog.created.success"))
    // and redirect to the blogs index page
    return c.redirect(302, "blogpostpath()", render.data{"slug": blog.slug})
}

new.html 看起来像这样:



<%= form_for(blog, {action: blogPath(), method: "POST"}) { %>
<%= partial("blogs/form.html") %>
Cancel
<% } %>

我遇到的问题是,当我尝试进行重定向时,它指向正确的网址 localhost:3000/blog/post/my-blog-post-here,但主体正在尝试使用blogs/index.html 模板而不是 blogs/show.html。那么,我需要做什么才能使重定向指向正确的 url 并包含正确的正文?我尝试将 <%= form_for(blog, {action: blogpath(), method: "post"}) { %> 设置为 <%= form_for(blog, {action: blogpostpath(), method: "post" }) { %>new.html 中,但是当我转到 localhost:3000/blog/new 时,我收到一个错误,需要 slug。


解决方案


看起来像是路由问题。 我偶然发现了这种问题。 这与路线指定的顺序有关。 路由器对顺序敏感;它将路由到第一个匹配的声明... 也许在你的情况下,第一个匹配的路由是“/” 我不是 100% 确定,但尝试相反的方式:

blogGroup.GET("/post/{slug}", b.Show)

blogGroup.GET("/post/{slug}/edit", b.Edit)

blogGroup.GET("/", b.List) blogGroup.GET("/new", b.New)

到这里,我们也就讲完了《如何实现在新贴网址中进行重定向以显示布法罗的贴文》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>