refactor: http request binding (#38971)

Better than before, still not good enough (more work can be done in the
future)

And add the missing error handling in the PrivateContext "bind"
middleware.

By the way, picked some "TrimSpace" changes from "fix: trim whitespace
from SMTP address and port - #38934" (fix #38926)
This commit is contained in:
wxiaoguang
2026-08-19 14:15:42 +08:00
committed by GitHub
parent 6c425fae6e
commit 6904f6480c
21 changed files with 265 additions and 419 deletions
+6 -13
View File
@@ -15,33 +15,26 @@ import (
"gitea.dev/modules/reqctx"
"gitea.dev/modules/setting"
"gitea.dev/modules/translation"
"gitea.dev/modules/validation"
"gitea.dev/modules/web/middleware"
"gitea.dev/modules/web/types"
"gitea.com/go-chi/binding"
"github.com/go-chi/chi/v5"
)
// Bind binding the request form to a form object and assign context data
func Bind[T interface {
*E
middleware.Form
}, E any]() http.HandlerFunc {
func Bind[T middleware.Form]() http.HandlerFunc {
return func(resp http.ResponseWriter, req *http.Request) {
form, errs := middleware.BindFormValidate[T](req, validation.Binder())
ctx := reqctx.FromContext(req.Context())
data := ctx.GetData()
locale := ctx.Value(translation.ContextKey).(translation.Locale) //nolint:forcetypeassert // must exist
obj := new(E)
var form T = obj
vctx := &middleware.ValidateContext{Locale: locale, Data: data, Req: req, Resp: resp}
errs := binding.Bind(req, obj)
errs = form.Validate(vctx, errs)
SetForm(data, obj)
SetForm(data, form)
// Legacy template error handling: try to restore the form's values as much as possible,
// especially for RenderWithErrDeprecated to re-render the form with errors.
middleware.AssignForm(obj, data)
middleware.AssignForm(form, data)
errorMessage, errorFieldName, _ := middleware.BuildValidationErrorForUser(form, locale, errs)
if errorMessage != "" {
data["HasError"] = true