utils.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package adaptor
  2. import (
  3. "errors"
  4. "fmt"
  5. "reflect"
  6. "github.com/bytedance/sonic"
  7. )
  8. type BasicError[T any] struct {
  9. error T
  10. statusCode int
  11. }
  12. func (e BasicError[T]) MarshalJSON() ([]byte, error) {
  13. return sonic.Marshal(e.error)
  14. }
  15. func (e BasicError[T]) StatusCode() int {
  16. return e.statusCode
  17. }
  18. func (e BasicError[T]) Error() string {
  19. return fmt.Sprintf("status code: %d, error: %v", e.statusCode, e.error)
  20. }
  21. func NewError[T any](statusCode int, err T) Error {
  22. return BasicError[T]{
  23. error: err,
  24. statusCode: statusCode,
  25. }
  26. }
  27. func ValidateConfigTemplate(template ConfigTemplate) error {
  28. if template.Name == "" {
  29. return errors.New("config template is invalid: name is empty")
  30. }
  31. if template.Type == "" {
  32. return fmt.Errorf("config template %s is invalid: type is empty", template.Name)
  33. }
  34. if template.Example != nil {
  35. if err := ValidateConfigTemplateValue(template, template.Example); err != nil {
  36. return fmt.Errorf("config template %s is invalid: %w", template.Name, err)
  37. }
  38. }
  39. return nil
  40. }
  41. func ValidateConfigTemplateValue(template ConfigTemplate, value any) error {
  42. if template.Validator == nil {
  43. return nil
  44. }
  45. switch template.Type {
  46. case ConfigTypeString:
  47. _, ok := value.(string)
  48. if !ok {
  49. return fmt.Errorf("config template %s is invalid: value is not a string", template.Name)
  50. }
  51. case ConfigTypeNumber:
  52. switch value.(type) {
  53. case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64:
  54. return nil
  55. default:
  56. return fmt.Errorf("config template %s is invalid: value is not a number", template.Name)
  57. }
  58. case ConfigTypeBool:
  59. _, ok := value.(bool)
  60. if !ok {
  61. return fmt.Errorf("config template %s is invalid: value is not a bool", template.Name)
  62. }
  63. case ConfigTypeObject:
  64. if reflect.TypeOf(value).Kind() != reflect.Map &&
  65. reflect.TypeOf(value).Kind() != reflect.Struct {
  66. return fmt.Errorf("config template %s is invalid: value is not a object", template.Name)
  67. }
  68. }
  69. if err := template.Validator(value); err != nil {
  70. return fmt.Errorf(
  71. "config template %s(%s) is invalid: %w",
  72. template.Name,
  73. template.Name,
  74. err,
  75. )
  76. }
  77. return nil
  78. }