service.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package service
  2. import (
  3. "context"
  4. "errors"
  5. "strings"
  6. )
  7. // Service constants
  8. const (
  9. StrMaxSize = 1024
  10. )
  11. // Service errors
  12. var (
  13. ErrMaxSize = errors.New("maximum size of 1024 bytes exceeded")
  14. ErrStrValue = errors.New("error str value to Integer")
  15. )
  16. // Service Define a service interface
  17. type Service interface {
  18. // Concat a and b
  19. Concat(a, b string) (string, error)
  20. // a,b pkg string value
  21. Diff(ctx context.Context, a, b string) (string, error)
  22. // HealthCheck check service health status
  23. HealthCheck() bool
  24. }
  25. //ArithmeticService implement Service interface
  26. type StringService struct {
  27. }
  28. func (s StringService) Concat(a, b string) (string, error) {
  29. // test for length overflow
  30. if len(a)+len(b) > StrMaxSize {
  31. return "", ErrMaxSize
  32. }
  33. return a + b, nil
  34. }
  35. func (s StringService) Diff(ctx context.Context, a, b string) (string, error) {
  36. if len(a) < 1 || len(b) < 1 {
  37. return "", nil
  38. }
  39. res := ""
  40. if len(a) >= len(b) {
  41. for _, char := range b {
  42. if strings.Contains(a, string(char)) {
  43. res = res + string(char)
  44. }
  45. }
  46. } else {
  47. for _, char := range a {
  48. if strings.Contains(b, string(char)) {
  49. res = res + string(char)
  50. }
  51. }
  52. }
  53. return res, nil
  54. }
  55. // HealthCheck implement Service method
  56. // 用于检查服务的健康状态,这里仅仅返回true。
  57. func (s StringService) HealthCheck() bool {
  58. return true
  59. }
  60. // ServiceMiddleware define service middleware
  61. type ServiceMiddleware func(Service) Service