param.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package hero
  2. import (
  3. "reflect"
  4. "github.com/kataras/iris/context"
  5. )
  6. // weak because we don't have access to the path, neither
  7. // the macros, so this is just a guess based on the index of the path parameter,
  8. // the function's path parameters should be like a chain, in the same order as
  9. // the caller registers a route's path.
  10. // A context or any value(s) can be in front or back or even between them.
  11. type params struct {
  12. // the next function input index of where the next path parameter
  13. // should be inside the CONTEXT.
  14. next int
  15. }
  16. func (p *params) resolve(index int, typ reflect.Type) (reflect.Value, bool) {
  17. currentParamIndex := p.next
  18. v, ok := resolveParam(currentParamIndex, typ)
  19. p.next = p.next + 1
  20. return v, ok
  21. }
  22. func resolveParam(currentParamIndex int, typ reflect.Type) (reflect.Value, bool) {
  23. var fn interface{}
  24. switch typ.Kind() {
  25. case reflect.Int:
  26. fn = func(ctx context.Context) int {
  27. // the second "ok/found" check is not necessary,
  28. // because even if the entry didn't found on that "index"
  29. // it will return an empty entry which will return the
  30. // default value passed from the xDefault(def) because its `ValueRaw` is nil.
  31. entry, _ := ctx.Params().GetEntryAt(currentParamIndex)
  32. v, _ := entry.IntDefault(0)
  33. return v
  34. }
  35. case reflect.Int64:
  36. fn = func(ctx context.Context) int64 {
  37. entry, _ := ctx.Params().GetEntryAt(currentParamIndex)
  38. v, _ := entry.Int64Default(0)
  39. return v
  40. }
  41. case reflect.Bool:
  42. fn = func(ctx context.Context) bool {
  43. entry, _ := ctx.Params().GetEntryAt(currentParamIndex)
  44. v, _ := entry.BoolDefault(false)
  45. return v
  46. }
  47. case reflect.String:
  48. fn = func(ctx context.Context) string {
  49. entry, _ := ctx.Params().GetEntryAt(currentParamIndex)
  50. // print(entry.Key + " with index of: ")
  51. // print(currentParamIndex)
  52. // println(" and value: " + entry.String())
  53. return entry.String()
  54. }
  55. default:
  56. return reflect.Value{}, false
  57. }
  58. return reflect.ValueOf(fn), true
  59. }