|
1 | 1 | package nginx
|
2 | 2 |
|
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "strings" |
| 6 | +) |
| 7 | + |
| 8 | +// ParseLBMethod parses method and matches it to a corresponding load balancing method in NGINX. An error is returned if method is not valid |
3 | 9 | func ParseLBMethod(method string) (string, error) {
|
| 10 | + method = strings.TrimSpace(method) |
4 | 11 | if method == "round_robin" {
|
5 | 12 | return "", nil
|
6 | 13 | }
|
7 |
| - return method, nil |
| 14 | + if strings.HasPrefix(method, "hash") { |
| 15 | + method, err := validateHashLBMethod(method) |
| 16 | + return method, err |
| 17 | + } |
| 18 | + |
| 19 | + if method == "least_conn" || method == "ip_hash" { |
| 20 | + return method, nil |
| 21 | + } |
| 22 | + return "", fmt.Errorf("Invalid load balancing method: %q", method) |
| 23 | +} |
| 24 | + |
| 25 | +var nginxPlusLBValidInput = map[string]bool{ |
| 26 | + "least_time": true, |
| 27 | + "last_byte": true, |
| 28 | + "least_conn": true, |
| 29 | + "ip_hash": true, |
| 30 | + "least_time header": true, |
| 31 | + "least_time last_byte": true, |
| 32 | + "least_time header inflight": true, |
| 33 | + "least_time last_byte inflight": true, |
8 | 34 | }
|
9 | 35 |
|
| 36 | +// ParseLBMethodForPlus parses method and matches it to a corresponding load balancing method in NGINX Plus. An error is returned if method is not valid |
10 | 37 | func ParseLBMethodForPlus(method string) (string, error) {
|
| 38 | + method = strings.TrimSpace(method) |
11 | 39 | if method == "round_robin" {
|
12 | 40 | return "", nil
|
13 | 41 | }
|
14 |
| - return method, nil |
| 42 | + if strings.HasPrefix(method, "hash") { |
| 43 | + method, err := validateHashLBMethod(method) |
| 44 | + return method, err |
| 45 | + } |
| 46 | + |
| 47 | + if _, exists := nginxPlusLBValidInput[method]; exists { |
| 48 | + return method, nil |
| 49 | + } |
| 50 | + return "", fmt.Errorf("Invalid load balancing method: %q", method) |
| 51 | +} |
| 52 | + |
| 53 | +func validateHashLBMethod(method string) (string, error) { |
| 54 | + keyWords := strings.Split(method, " ") |
| 55 | + if keyWords[0] == "hash" { |
| 56 | + if len(keyWords) == 2 || len(keyWords) == 3 && keyWords[2] == "consistent" { |
| 57 | + return method, nil |
| 58 | + } |
| 59 | + } |
| 60 | + return "", fmt.Errorf("Invalid load balancing method: %q", method) |
15 | 61 | }
|
0 commit comments