duanshan1977 2017-05-17 15:05
浏览 10
已采纳

根据失败的POST请求呈现模板[golang]

I want to handle the errors of a POST request and re-render the form with the errors displayed above it, but the only solution to handling errors I see is http.Error() but this returns a plaintext response, not an HTML page. Is there a way to executeTemplate() and re-render the html page with the form? Am I supposed to redirect the user to the same page? If so, how do I pass the error information to that redirected page?

Edit: So, when I use this code, and try to executeTemplate, the Post request returns a 200 status code (which is wrong) and it re-renders blank page, not the template I specified.

func PostSignup(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
if r.Method != http.MethodPost {
    http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)
    return
}

usr := users.User{}
usr.Username = r.FormValue("username")
usr.Email = r.FormValue("email")
usr.Hash = r.FormValue("password")

errors := CredErrors{}
errors.Error = "Username cannot be blank"
if usr.Username == "" {
    // http.Error(w, "Username cannot be blank.", 400)
    tpl.ExecuteTemplate(w, "signup.gothml", errors)
    return
}
  • 写回答

1条回答 默认 最新

  • dslijian2015 2017-05-17 15:09
    关注

    The answer is in the question:

    Is there a way to executeTemplate() and re-render the html page with the form?

    Yes, use executeTemplate to re-render the form. http.Error() is for returning HTTP errors, not form validation errors. If the form fails validation and you want to redisplay it, do just that - render the form out to the browser again, with whatever validation errors/prepopulation/whatever you want to display.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 关于python拓展屏使用pyautogui.screenshot无法截图的问题
  • ¥15 有偿求答 无导出权限怎么快速导出企业微信微文档
  • ¥15 求解答,怎么数码管中这么加入闹钟或者传感器,这应该怎么加入相应的代码
  • ¥15 scottplot5
  • ¥30 想问问这个建模怎么编程没有思路
  • ¥15 关于imageENview(ImageEN)中新建图层并根据鼠标位置添加图标
  • ¥100 用两台电脑局域联网进行MT5的EA参数优化,但是连接不上,日志提示:
  • ¥15 FastAPI报错: AsyncSession不是有效Pydantic类型
  • ¥50 这Mac系统提示虚拟内存不足,怎么解决
  • ¥15 Rs232电路无法收发数据,求帮助