sq.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package ultraviolet
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. type SQ struct {
  7. value reflect.Value
  8. }
  9. func NewSQ(value any) *SQ {
  10. return &SQ{
  11. value: reflect.ValueOf(value).Elem(),
  12. }
  13. }
  14. func newSQInternal(value reflect.Value) *SQ {
  15. return &SQ{
  16. value: value,
  17. }
  18. }
  19. func (this *SQ) Field(name string) *SQ {
  20. if this.value.Kind() != reflect.Struct {
  21. return nil
  22. }
  23. return newSQInternal(
  24. this.value.FieldByName(name),
  25. )
  26. }
  27. func (this *SQ) Length() int {
  28. return this.value.Len()
  29. }
  30. func (this *SQ) Index(index int) *SQ {
  31. if this.value.Kind() != reflect.Slice {
  32. return nil
  33. }
  34. return newSQInternal(
  35. this.value.Index(index),
  36. )
  37. }
  38. func (this *SQ) Keys() []string {
  39. result := []string{}
  40. for _, key := range this.value.MapKeys() {
  41. result = append(result, key.String())
  42. }
  43. return result
  44. }
  45. func (this *SQ) Key(key string) *SQ {
  46. if this.value.Kind() != reflect.Map {
  47. return nil
  48. }
  49. return newSQInternal(
  50. this.value.MapIndex(reflect.ValueOf(key)),
  51. )
  52. }
  53. func (this *SQ) Value() any {
  54. if this.value.Kind() == reflect.Int {
  55. return fmt.Sprintf("%d", this.value.Int())
  56. }
  57. return this.value.String()
  58. }
  59. func (this *SQ) ValueInt() any {
  60. return this.value.Int()
  61. }
  62. func (this *SQ) ValueString() any {
  63. return this.value.String()
  64. }