Skip to content

Commit 8c384f9

Browse files
authored
impr(swagger): fix ordering for proper info displayed (#1178)
1 parent 5a3fe48 commit 8c384f9

1 file changed

Lines changed: 35 additions & 8 deletions

File tree

server/swagger.go

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package server
33
import (
44
"fmt"
55
"net/http"
6+
"os"
7+
"sort"
68

79
"github.com/ctfer-io/chall-manager/global"
810
"github.com/ctfer-io/chall-manager/pkg/swagger"
@@ -14,28 +16,53 @@ func addSwagger(mux *http.ServeMux) {
1416
_, span := global.Tracer.Start(r.Context(), "swagger")
1517
defer span.End()
1618

17-
swaggers := []string{
18-
"challenge",
19-
"instance",
20-
"common", // must be last to overwrite previous attributes
21-
}
2219
mergedSwagger := swagger.NewMerger()
23-
for _, swagger := range swaggers {
24-
swaggerPath := fmt.Sprintf("./gen/api/v1/%[1]s/%[1]s.swagger.json", swagger)
20+
ds, err := os.ReadDir("./gen/api/v1")
21+
if err != nil {
22+
http.Error(w, "Reading generated swagger directories", http.StatusInternalServerError)
23+
return
24+
}
25+
sortDirs(ds)
26+
for _, d := range ds {
27+
swaggerPath := fmt.Sprintf("./gen/api/v1/%[1]s/%[1]s.swagger.json", d.Name())
2528
if err := mergedSwagger.AddFile(swaggerPath); err != nil {
2629
http.Error(w, "Merging swaggers", http.StatusInternalServerError)
2730
return
2831
}
2932
}
33+
3034
b, err := mergedSwagger.MarshalJSON()
3135
if err != nil {
3236
http.Error(w, "Exporting merged swagger", http.StatusInternalServerError)
3337
return
3438
}
3539
if _, err := w.Write(b); err != nil {
36-
http.Error(w, "Writing merged swagger", http.StatusInternalServerError)
40+
http.Error(w, "Writing merged swagger", http.StatusInternalServerError)
3741
return
3842
}
3943
})
4044
mux.Handle("/swagger/", http.StripPrefix("/swagger/", http.FileServer(http.FS(swaggerui.Content))))
4145
}
46+
47+
// sorts the directories in alphabetic order, and if provided, set
48+
// the "common" directory last (should contain the swagger global infos).
49+
func sortDirs(entries []os.DirEntry) {
50+
sort.SliceStable(entries, func(i, j int) bool {
51+
nameI := entries[i].Name()
52+
nameJ := entries[j].Name()
53+
54+
// Check if either is the "common" directory
55+
isCommonI := entries[i].IsDir() && nameI == "common"
56+
isCommonJ := entries[j].IsDir() && nameJ == "common"
57+
58+
if isCommonI && !isCommonJ {
59+
return false // i should come after j
60+
}
61+
if !isCommonI && isCommonJ {
62+
return true // i should come before j
63+
}
64+
65+
// Otherwise sort alphabetically
66+
return nameI < nameJ
67+
})
68+
}

0 commit comments

Comments
 (0)