在失败的POST请求时渲染一个模板 [golang]

huangapple go评论94阅读模式
英文:

Render a template upon failed POST request [golang]

问题

我想处理一个POST请求的错误,并重新渲染带有错误信息的表单,但是我看到的处理错误的唯一解决方案是使用http.Error(),但这只返回纯文本响应,而不是HTML页面。有没有办法使用executeTemplate()重新渲染带有表单的HTML页面?我应该将用户重定向到同一个页面吗?如果是这样,我如何将错误信息传递给重定向的页面?

编辑:所以,当我使用这段代码并尝试执行executeTemplate时,POST请求返回了一个错误的200状态码,并重新渲染了一个空白页面,而不是我指定的模板。

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
	}

以上是您提供的代码。

英文:

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

得分: 0

答案就在问题中:

> 有没有一种方法可以使用executeTemplate()重新渲染带有表单的HTML页面?

是的,使用executeTemplate来重新渲染表单。http.Error()用于返回HTTP错误,而不是表单验证错误。如果表单验证失败并且您想要重新显示它,只需这样做-再次将表单渲染到浏览器中,包括您想要显示的任何验证错误/预填充/其他内容。

英文:

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.

huangapple
  • 本文由 发表于 2017年5月17日 23:05:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/44028578.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定