validation.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. // валидатор
  6. "github.com/asaskevich/govalidator"
  7. // парсинг параметров в структуру
  8. "github.com/gorilla/schema"
  9. )
  10. // http://127.0.0.1:8080/?to=v.romanov@corp.mail.ru&priority=low&subject=Hello!&inner=ignored&id=12&flag=23
  11. type SendMessage struct {
  12. Id int `valid:",optional"`
  13. Priority string `valid:"in(low|normal|high)"`
  14. Recipient string `schema:"to" valid:"email"`
  15. Subject string `valid:"msgSubject"`
  16. Inner string `schema:"-" valid:"-"`
  17. flag int
  18. }
  19. func handler(w http.ResponseWriter, r *http.Request) {
  20. w.Write([]byte("request " + r.URL.String() + "\n\n"))
  21. msg := &SendMessage{}
  22. decoder := schema.NewDecoder()
  23. decoder.IgnoreUnknownKeys(true)
  24. err := decoder.Decode(msg, r.URL.Query())
  25. if err != nil {
  26. fmt.Println(err)
  27. http.Error(w, "internal", 500)
  28. return
  29. }
  30. w.Write([]byte(fmt.Sprintf("Msg: %#v\n\n", msg)))
  31. _, err = govalidator.ValidateStruct(msg)
  32. if err != nil {
  33. if allErrs, ok := err.(govalidator.Errors); ok {
  34. for _, fld := range allErrs.Errors() {
  35. data := []byte(fmt.Sprintf("field: %#v\n\n", fld))
  36. w.Write(data)
  37. }
  38. }
  39. w.Write([]byte(fmt.Sprintf("error: %s\n\n", err)))
  40. } else {
  41. w.Write([]byte(fmt.Sprintf("msg is correct\n\n")))
  42. }
  43. }
  44. func main() {
  45. http.HandleFunc("/", handler)
  46. fmt.Println("starting server at :8080")
  47. http.ListenAndServe(":8080", nil)
  48. }
  49. func init() {
  50. govalidator.CustomTypeTagMap.Set("msgSubject", govalidator.CustomTypeValidator(func(i interface{}, o interface{}) bool {
  51. subject, ok := i.(string)
  52. if !ok {
  53. return false
  54. }
  55. if len(subject) == 0 || len(subject) > 10 {
  56. return false
  57. }
  58. return true
  59. }))
  60. }