util.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. fromPort, err := strconv.Atoi(arrs[2])
  25. if err != nil {
  26. return nil, fmt.Errorf("error range port from")
  27. }
  28. builder.rangePortFrom = fromPort
  29. toPort, err := strconv.Atoi(arrs[3])
  30. if err != nil {
  31. return nil, fmt.Errorf("error range port to")
  32. }
  33. builder.rangePortTo = toPort
  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. }