util.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package port
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. )
  7. const (
  8. NameDelimiter = "_"
  9. )
  10. type NameOption func(*nameBuilder) *nameBuilder
  11. type nameBuilder struct {
  12. name string
  13. rangePortFrom int
  14. rangePortTo int
  15. }
  16. func unmarshalFromName(name string) (*nameBuilder, error) {
  17. var builder nameBuilder
  18. arrs := strings.Split(name, NameDelimiter)
  19. switch len(arrs) {
  20. case 2:
  21. builder.name = arrs[1]
  22. case 4:
  23. builder.name = arrs[1]
  24. if fromPort, err := strconv.Atoi(arrs[2]); err != nil {
  25. return nil, fmt.Errorf("error range port from")
  26. } else {
  27. builder.rangePortFrom = fromPort
  28. }
  29. if toPort, err := strconv.Atoi(arrs[3]); err != nil {
  30. return nil, fmt.Errorf("error range port to")
  31. } else {
  32. builder.rangePortTo = toPort
  33. }
  34. default:
  35. return nil, fmt.Errorf("error port name format")
  36. }
  37. return &builder, nil
  38. }
  39. func (builder *nameBuilder) String() string {
  40. name := fmt.Sprintf("Port%s%s", NameDelimiter, builder.name)
  41. if builder.rangePortFrom > 0 && builder.rangePortTo > 0 && builder.rangePortTo > builder.rangePortFrom {
  42. name += fmt.Sprintf("%s%d%s%d", NameDelimiter, builder.rangePortFrom, NameDelimiter, builder.rangePortTo)
  43. }
  44. return name
  45. }
  46. func WithRangePorts(from, to int) NameOption {
  47. return func(builder *nameBuilder) *nameBuilder {
  48. builder.rangePortFrom = from
  49. builder.rangePortTo = to
  50. return builder
  51. }
  52. }
  53. func GenName(name string, options ...NameOption) string {
  54. name = strings.ReplaceAll(name, "-", "")
  55. name = strings.ReplaceAll(name, "_", "")
  56. builder := &nameBuilder{name: name}
  57. for _, option := range options {
  58. builder = option(builder)
  59. }
  60. return builder.String()
  61. }