@@ -3,6 +3,7 @@ package translator
33import (
44 "encoding/json"
55 "fmt"
6+ "sort"
67 "strings"
78
89 "github.com/api7/gopkg/pkg/log"
@@ -341,6 +342,33 @@ func (t *Translator) translateBackendRef(tctx *provider.TranslateContext, ref ga
341342 return t .translateEndpointSlice (portName , weight , endpointSlices )
342343}
343344
345+ // calculateMatchPriority calculate the priority of HTTPRouteMatch, according to the Gateway API specification
346+ // the higher the return value, the higher the priority
347+ func calculateMatchPriority (match * gatewayv1.HTTPRouteMatch ) int64 {
348+ var score int64 = 0
349+
350+ // 1. Exact path matches have the highest priority
351+ if match .Path != nil && match .Path .Type != nil && * match .Path .Type == gatewayv1 .PathMatchExact {
352+ score += 10000
353+ } else if match .Path != nil && match .Path .Type != nil && * match .Path .Type == gatewayv1 .PathMatchPathPrefix && match .Path .Value != nil {
354+ // 2. Prefix path matches, the longer the string, the higher the priority
355+ score += 1000 + int64 (len (* match .Path .Value ))
356+ }
357+
358+ // 3. Method matching
359+ if match .Method != nil {
360+ score += 100
361+ }
362+
363+ // 4. Header matching, the more headers, the higher the priority
364+ score += int64 (len (match .Headers ) * 10 )
365+
366+ // 5. Query parameter matching, the more query parameters, the higher the priority
367+ score += int64 (len (match .QueryParams ))
368+
369+ return score
370+ }
371+
344372func (t * Translator ) TranslateHTTPRoute (tctx * provider.TranslateContext , httpRoute * gatewayv1.HTTPRoute ) (* TranslateResult , error ) {
345373 result := & TranslateResult {}
346374
@@ -388,6 +416,11 @@ func (t *Translator) TranslateHTTPRoute(tctx *provider.TranslateContext, httpRou
388416 },
389417 },
390418 }
419+ } else {
420+ // Sort the matches by priority
421+ sort .Slice (matches , func (a , b int ) bool {
422+ return calculateMatchPriority (& matches [a ]) > calculateMatchPriority (& matches [b ])
423+ })
391424 }
392425
393426 routes := []* adctypes.Route {}
@@ -402,6 +435,11 @@ func (t *Translator) TranslateHTTPRoute(tctx *provider.TranslateContext, httpRou
402435 route .ID = id .GenID (name )
403436 route .Labels = labels
404437 route .EnableWebsocket = ptr .To (true )
438+
439+ // Set the route priority
440+ priority := calculateMatchPriority (& match )
441+ route .Priority = & priority
442+
405443 routes = append (routes , route )
406444 }
407445 t .fillHTTPRoutePoliciesForHTTPRoute (tctx , routes , rule )
0 commit comments