log_list.go 1008 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package nginx_log
  2. import (
  3. "slices"
  4. )
  5. // typeToInt converts log type string to a sortable integer
  6. // "access" = 0, "error" = 1
  7. func typeToInt(t string) int {
  8. if t == "access" {
  9. return 0
  10. }
  11. return 1
  12. }
  13. // sortCompare compares two log entries based on the specified key and order
  14. // Returns true if i should come after j in the sorted list
  15. func sortCompare(i, j *NginxLogCache, key string, order string) bool {
  16. flag := false
  17. switch key {
  18. case "type":
  19. flag = typeToInt(i.Type) > typeToInt(j.Type)
  20. default:
  21. fallthrough
  22. case "name":
  23. flag = i.Name > j.Name
  24. }
  25. if order == "asc" {
  26. flag = !flag
  27. }
  28. return flag
  29. }
  30. // Sort sorts a list of NginxLogCache entries by the specified key and order
  31. // Supported keys: "type", "name"
  32. // Supported orders: "asc", "desc"
  33. func Sort(key string, order string, configs []*NginxLogCache) []*NginxLogCache {
  34. slices.SortStableFunc(configs, func(i, j *NginxLogCache) int {
  35. if sortCompare(i, j, key, order) {
  36. return 1
  37. }
  38. return -1
  39. })
  40. return configs
  41. }