Skip to content

Commit b455d5b

Browse files
committed
fix(openapi): 解决操作ID生成和重复问题
- 修正 HandlerName 中的路径分隔符和点,使其在操作ID中有效替换为下划线 - 在生成操作ID时,结合路由组名称前缀,提高ID唯一性和可读性 - 添加对操作ID重复的检测机制,遇重复时自动添加递增后缀避免冲突 - 确保生成的操作ID在整个生成器中唯一,防止运行时错误
1 parent 784a6a5 commit b455d5b

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

fizz.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,14 @@ func (g *RouterGroup) Handle(path, method string, infos []OperationOption, handl
207207

208208
// Set an operation ID if none is provided.
209209
if oi.ID == "" {
210-
oi.ID = hfunc.HandlerName()
210+
handlerName := hfunc.HandlerName()
211+
handlerName = strings.ReplaceAll(handlerName, "/", "_")
212+
handlerName = strings.ReplaceAll(handlerName, ".", "_")
213+
if g.Name != "" {
214+
oi.ID = g.Name + "_" + handlerName
215+
} else {
216+
oi.ID = handlerName
217+
}
211218
}
212219
oi.StatusCode = hfunc.GetDefaultStatusCode()
213220
requestMediaType := hfunc.GetRequestMediaType()

openapi/generator.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -244,8 +244,15 @@ func (g *Generator) AddOperation(path, method, tag, requestMediaType, responseMe
244244

245245
if info != nil {
246246
// Ensure that the provided operation ID is unique.
247-
if _, ok := g.operationsIDS[info.ID]; ok {
248-
return nil, fmt.Errorf("ID %s is already used by another operation", info.ID)
247+
// If duplicate, append suffix to make it unique.
248+
baseID := info.ID
249+
counter := 0
250+
for {
251+
if _, ok := g.operationsIDS[info.ID]; !ok {
252+
break
253+
}
254+
counter++
255+
info.ID = fmt.Sprintf("%s_%d", baseID, counter)
249256
}
250257
g.operationsIDS[info.ID] = struct{}{}
251258
}

0 commit comments

Comments
 (0)