2
2
package nat
3
3
4
4
import (
5
+ "errors"
5
6
"fmt"
6
7
"net"
7
8
"strconv"
@@ -107,13 +108,14 @@ func SplitProtoPort(rawPort string) (string, string) {
107
108
return parts [1 ], parts [0 ]
108
109
}
109
110
110
- func validateProto (proto string ) bool {
111
- for _ , availableProto := range []string {"tcp" , "udp" , "sctp" } {
112
- if availableProto == proto {
113
- return true
114
- }
111
+ func validateProto (proto string ) error {
112
+ switch proto {
113
+ case "tcp" , "udp" , "sctp" :
114
+ // All good
115
+ return nil
116
+ default :
117
+ return errors .New ("invalid proto: " + proto )
115
118
}
116
- return false
117
119
}
118
120
119
121
// ParsePortSpecs receives port specs in the format of ip:public:private/proto and parses
@@ -169,9 +171,12 @@ func splitParts(rawport string) (string, string, string) {
169
171
170
172
// ParsePortSpec parses a port specification string into a slice of PortMappings
171
173
func ParsePortSpec (rawPort string ) ([]PortMapping , error ) {
172
- var proto string
173
174
ip , hostPort , containerPort := splitParts (rawPort )
174
- proto , containerPort = SplitProtoPort (containerPort )
175
+ proto , containerPort := SplitProtoPort (containerPort )
176
+ proto = strings .ToLower (proto )
177
+ if err := validateProto (proto ); err != nil {
178
+ return nil , err
179
+ }
175
180
176
181
if ip != "" && ip [0 ] == '[' {
177
182
// Strip [] from IPV6 addresses
@@ -210,10 +215,6 @@ func ParsePortSpec(rawPort string) ([]PortMapping, error) {
210
215
}
211
216
}
212
217
213
- if ! validateProto (strings .ToLower (proto )) {
214
- return nil , fmt .Errorf ("invalid proto: %s" , proto )
215
- }
216
-
217
218
ports := []PortMapping {}
218
219
for i := uint64 (0 ); i <= (endPort - startPort ); i ++ {
219
220
containerPort = strconv .FormatUint (startPort + i , 10 )
@@ -223,18 +224,17 @@ func ParsePortSpec(rawPort string) ([]PortMapping, error) {
223
224
// Set hostPort to a range only if there is a single container port
224
225
// and a dynamic host port.
225
226
if startPort == endPort && startHostPort != endHostPort {
226
- hostPort = fmt . Sprintf ( "%s-%s" , hostPort , strconv .FormatUint (endHostPort , 10 ) )
227
+ hostPort = hostPort + "-" + strconv .FormatUint (endHostPort , 10 )
227
228
}
228
- port , err := NewPort (strings . ToLower ( proto ) , containerPort )
229
+ port , err := NewPort (proto , containerPort )
229
230
if err != nil {
230
231
return nil , err
231
232
}
232
233
233
- binding := PortBinding {
234
- HostIP : ip ,
235
- HostPort : hostPort ,
236
- }
237
- ports = append (ports , PortMapping {Port : port , Binding : binding })
234
+ ports = append (ports , PortMapping {
235
+ Port : port ,
236
+ Binding : PortBinding {HostIP : ip , HostPort : hostPort },
237
+ })
238
238
}
239
239
return ports , nil
240
240
}
0 commit comments