Common isomorphic functionality in one kit.

form.go 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // The Isomorphic Go Project
  2. // Copyright (c) Wirecog, LLC. All rights reserved.
  3. // Use of this source code is governed by a BSD-style
  4. // license, which can be found in the LICENSE file.
  5. package isokit
  6. import (
  7. "net/http"
  8. "honnef.co/go/js/dom"
  9. )
  10. type Form interface {
  11. Validate() bool
  12. AutofillFields() []string
  13. Fields() map[string]string
  14. Errors() map[string]string
  15. // SetError(key string, message string)
  16. }
  17. type FormParams struct {
  18. ResponseWriter http.ResponseWriter
  19. Request *http.Request
  20. FormElement *dom.HTMLFormElement
  21. UseFormFieldsForValidation bool
  22. FormFields map[string]string
  23. }
  24. func FormValue(fp *FormParams, key string) string {
  25. var result string
  26. if OperatingEnvironment() == ServerEnvironment && fp.Request == nil {
  27. return ""
  28. }
  29. switch OperatingEnvironment() {
  30. case ServerEnvironment:
  31. if fp.UseFormFieldsForValidation == true {
  32. result = fp.FormFields[key]
  33. } else {
  34. result = fp.Request.FormValue(key)
  35. }
  36. case WebBrowserEnvironment:
  37. field := fp.FormElement.QuerySelector("[name=" + key + "]")
  38. switch field.(type) {
  39. case *dom.HTMLInputElement:
  40. result = field.(*dom.HTMLInputElement).Value
  41. case *dom.HTMLTextAreaElement:
  42. result = field.(*dom.HTMLTextAreaElement).Value
  43. case *dom.HTMLSelectElement:
  44. result = field.(*dom.HTMLSelectElement).Value
  45. }
  46. }
  47. return result
  48. }