methodparams.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package param
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. //MethodParam keeps param information to be auto passed to controller methods
  7. type MethodParam struct {
  8. name string
  9. in paramType
  10. required bool
  11. defaultValue string
  12. }
  13. type paramType byte
  14. const (
  15. param paramType = iota
  16. path
  17. body
  18. header
  19. )
  20. //New creates a new MethodParam with name and specific options
  21. func New(name string, opts ...MethodParamOption) *MethodParam {
  22. return newParam(name, nil, opts)
  23. }
  24. func newParam(name string, parser paramParser, opts []MethodParamOption) (param *MethodParam) {
  25. param = &MethodParam{name: name}
  26. for _, option := range opts {
  27. option(param)
  28. }
  29. return
  30. }
  31. //Make creates an array of MethodParmas or an empty array
  32. func Make(list ...*MethodParam) []*MethodParam {
  33. if len(list) > 0 {
  34. return list
  35. }
  36. return nil
  37. }
  38. func (mp *MethodParam) String() string {
  39. options := []string{}
  40. result := "param.New(\"" + mp.name + "\""
  41. if mp.required {
  42. options = append(options, "param.IsRequired")
  43. }
  44. switch mp.in {
  45. case path:
  46. options = append(options, "param.InPath")
  47. case body:
  48. options = append(options, "param.InBody")
  49. case header:
  50. options = append(options, "param.InHeader")
  51. }
  52. if mp.defaultValue != "" {
  53. options = append(options, fmt.Sprintf(`param.Default("%s")`, mp.defaultValue))
  54. }
  55. if len(options) > 0 {
  56. result += ", "
  57. }
  58. result += strings.Join(options, ", ")
  59. result += ")"
  60. return result
  61. }