• swagger gin 文档接口排序,写了一个小工具,自定义接口排序


    起因没找到swagger 自定义接口排序

    代码原理就是替换 swag init 生成的docs.go paths 部分 ,取到swagger.json paths 部分排序,正则匹配docs.go paths 部分,然后通过自定义排序,替换paths部分,这个根据自定义的需求来

    代码如下

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"github.com/tidwall/gjson"
    	orderedmap "github.com/wk8/go-ordered-map/v2"
    	"log"
    	"os"
    	"regexp"
    	"sort"
    	"strconv"
    	"strings"
    )
    
    // GOOS=darwin GOARCH=arm64 go build -x -v -ldflags "-s -w" -o swagger_sort main.go
    type Endpoint struct {
    	Post struct {
    		Security    []map[string][]interface{} `json:"security"`
    		Description string                     `json:"description"`
    		Consumes    []string                   `json:"consumes"`
    		Produces    []string                   `json:"produces"`
    		Tags        []string                   `json:"tags"`
    		Summary     string                     `json:"summary"`
    		Parameters  []map[string]interface{}   `json:"parameters"`
    		Responses   map[string]interface{}     `json:"responses"`
    	} `json:"post"`
    }
    
    func main() {
    	goPath := os.Args[1]
    	swaggerPath := os.Args[2]
    	if goPath == "" || swaggerPath == "" {
    		log.Fatal("文件不存在")
    		return
    	}
    
    	// 从doc.go中读取内容
    	content, err := os.ReadFile(goPath)
    	if err != nil {
    		log.Fatalf("Error reading docs.go: %v", err)
    	}
    
    	newPathsContent := getNewContents(swaggerPath)
    	// 正则匹配 "paths" 及其后面的 {} 内容,但保留 "definitions"
    	r := regexp.MustCompile(`(?s)"paths": (\{.*?\}),\s*"definitions"`)
    	matches := r.FindStringSubmatch(string(content))
    	if matches == nil {
    		fmt.Println("No match found!")
    		return
    	}
    	//fmt.Println("Matched:", matches[1])
    
    
    	// Replace matched content in docs.go with newPathsContent
    	updatedContent := string(content)
    	updatedContent = strings.Replace(updatedContent, matches[1], newPathsContent, 1)
    
    	// Write the updated content back to docs.go
    	err = os.WriteFile(goPath, []byte(updatedContent), 0644)
    	if err != nil {
    		log.Fatalf("Error writing to docs.go: %v", err)
    	}
    
    	fmt.Println("Successfully wrote to test.js and updated docs.go!")
    }
    
    func extractNumberFromSummary(summary string) int {
    	parts := strings.Split(summary, ".")
    	if len(parts) > 0 {
    		num, err := strconv.Atoi(parts[0])
    		if err == nil {
    			return num
    		}
    	}
    	return 0
    }
    
    func getNewContents(swaggerPath string) string {
    	content, err := os.ReadFile(swaggerPath)
    
    	if err != nil {
    		log.Fatalf("Error reading swagger.json: %v", err)
    	}
    	str := gjson.Get(string(content), "paths").String()
    
    	var data map[string]Endpoint
    	if err := json.Unmarshal([]byte(str), &data); err != nil {
    		panic(err)
    	}
    
    	type PathItem struct {
    		Path string
    		Ep   Endpoint
    	}
    
    	var paths []PathItem
    	for k, v := range data {
    		paths = append(paths, PathItem{k, v})
    	}
    
    	sort.Slice(paths, func(i, j int) bool {
    		if len(paths[i].Ep.Post.Tags) > 0 {
    			if paths[i].Ep.Post.Tags[0] == paths[j].Ep.Post.Tags[0] {
    				numI := extractNumberFromSummary(paths[i].Ep.Post.Summary)
    				numJ := extractNumberFromSummary(paths[j].Ep.Post.Summary)
    				return numI < numJ
    			} else if strings.Contains(paths[i].Ep.Post.Tags[0], "测试") {
    				return false
    			} else {
    				return true
    			}
    		}
    		return true
    
    	})
    
    	//bytePath, _ := json.MarshalIndent(paths, "", "    ")
    	//fmt.Println(string(bytePath))
    
    	// 创建一个新的 ordered map
    	orderedData := orderedmap.New[string, Endpoint]()
    
    	// 从排序后的切片中填充 ordered map
    	for _, item := range paths {
    		orderedData.Set(item.Path, item.Ep)
    	}
    
    	// 编码 ordered map
    	sortedJSON, err := json.MarshalIndent(orderedData, "", "    ")
    	if err != nil {
    		panic(err)
    	}
    
    	fmt.Println(string(sortedJSON))
    	return string(sortedJSON)
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138

    我的排序效果

    在这里插入图片描述

  • 相关阅读:
    阿里OceanBase GitHub送礼刷Star引争议,CTO致歉
    【Spring Boot】RabbitMQ消息队列 — RabbitMQ入门
    【动画进阶】单标签下多色块随机文字随机颜色动画
    阿四的情绪波动
    TCO-PEG-N3|TCO-PEG-azide|反式环辛烯-聚乙二醇-叠氮-齐岳生物
    `算法竞赛题解` `LeetCode` 1044. 最长重复子串
    UML/SysML建模工具更新情况-截至2024年4月(1)5款-Trufun建模平台 v2024
    【机器学习】无监督学习中的基于内容过滤算法
    呼叫中心的实时语音分析
    【Python】函数式编程
  • 原文地址:https://blog.csdn.net/qq_36517296/article/details/133909389