constructors.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package forms
  2. import (
  3. "net/http"
  4. "strconv"
  5. )
  6. /* strFromPtr converts string pointer to a string */
  7. func strFromPtr(str *string) (s string) {
  8. if str != nil {
  9. s = *str
  10. }
  11. return
  12. }
  13. /* Generate new CharField field with type text */
  14. func NewCharField(name string, value *string) *FormField {
  15. return &FormField{
  16. Name: name,
  17. Value: strFromPtr(value),
  18. Kind: "text",
  19. }
  20. }
  21. /* Generate new integer type field */
  22. func NewIntField(name string, value int) *FormField {
  23. field := FormField{
  24. Name: name,
  25. Value: strconv.Itoa(value),
  26. Kind: "text",
  27. }
  28. field.AddValidator(ValidInt)
  29. return &field
  30. }
  31. /* Generate new password field */
  32. func NewPasswordField(name string) *FormField {
  33. return &FormField{
  34. Name: name,
  35. Kind: "password",
  36. }
  37. }
  38. /* Generate a new checkbox field */
  39. func NewCheckboxField(name string, checked bool) *FormField {
  40. return &FormField{
  41. Name: name,
  42. Checked: checked,
  43. Kind: "checkbox",
  44. }
  45. }
  46. /* Generate a new CSRF field */
  47. func NewCsrfField(w http.ResponseWriter, r *http.Request, secure bool) *FormField {
  48. return &FormField{
  49. Name: csrfFieldName,
  50. Value: csrfToken(w, r, secure),
  51. Kind: "hidden",
  52. Sticky: true,
  53. Validators: ValidatorsList{
  54. ValidCSRF(r),
  55. },
  56. }
  57. }
  58. /* Generate a new hidden text field */
  59. func NewHiddenField(name string, value *string) *FormField {
  60. return &FormField{
  61. Name: name,
  62. Value: strFromPtr(value),
  63. Kind: "hidden",
  64. }
  65. }