// Route parser, returns a IPRoutes structure or list of routes, all methods // are broken up to avoid duplicate unecessary json nesting package swModels import "regexp" var ( ROUTERE = regexp.MustCompile(`(?i)ip\s+route\s+(\S+)[ ]+(\S+)[ ]+(\S+)(\n|$)`) ) type ( IPRoutes struct { IPRoutes []*IPRoute `json:"routes"` } IPRoute struct { NextHop string `json:"next_hop"` Dest []*DestinationNetwork `json:"networks"` } DestinationNetwork struct { Network string `json:"network"` Netmask string `json:"netmask"` } ) // Method to call the route parser func (i *IPRoutes) Parse(s *string) { i.IPRoutes = RouteParse(s) } // Method to parse routes, will return a list or routes func RouteParse(s *string) (ipr []*IPRoute) { routeMap := make(map[string][]*DestinationNetwork) for _, r := range ROUTERE.FindAllStringSubmatch(*s, -1) { routeMap[r[3]] = append(routeMap[r[3]], &DestinationNetwork{ Network: r[1], Netmask: r[2], }) } for val, key := range routeMap { ipr = append(ipr, &IPRoute{ NextHop: val, Dest: key, }) } return } // method to call IPRoutesGetGateway func (i *IPRoutes) GetGateway(s string) *IPRoute { return IPRoutesGetGateway(i.IPRoutes, s) } // method to find a gateway given alist of routes and gateway func IPRoutesGetGateway(routes []*IPRoute, s string) *IPRoute { for _, r := range routes { if r.NextHop == s { return r } } return nil }