// test package server import ( "errors" "net/http" "git.runcible.io/learning/ratchet/internal/validator" "github.com/go-playground/form/v4" ) // Define a snippetCreateForm struct to represent the form data and validation // errors for the form fields. Note that all the struct fields are deliberately // exported (i.e. start with a capital letter). This is because struct fields // must be exported in order to be read by the html/template package when // rendering the template. // // Remove the explicit FieldErrors struct field and instead embed the Validator // struct. Embedding this means that our snippetCreateForm "inherits" all the // fields and methods of our Validator struct (including the FieldErrors field). // // MOVING TO go-playground/form // Update our snippetCreateForm struct to include struct tags which tell the // decoder how to map HTML form values into the different struct fields. So, for // example, here we're telling the decoder to store the value from the HTML form // input with the name "title" in the Title field. The struct tag `form:"-"` // tells the decoder to completely ignore a field during decoding. type snippetCreateForm struct { Title string `form:"title"` Content string `form:"content"` Expires int `form:"expires"` validator.Validator `form:"-"` } func decodePostForm(r *http.Request, fd *form.Decoder, dst any) error { err := r.ParseForm() if err != nil { return err } err = fd.Decode(dst, r.PostForm) if err != nil { var invalidDecoderError *form.InvalidDecoderError if errors.As(err, &invalidDecoderError) { // if called in the handler, recovery middleware // will log and send 500 response back panic(err) } return err } return nil }