1. 程式人生 > >gin使用中介軟體出錯後不能用return終止,而應該使用Abort實現

gin使用中介軟體出錯後不能用return終止,而應該使用Abort實現

gin使用中介軟體一般是在引擎Engine初始化的時候就繫結,也就是說在需要使用中介軟體才能訪問資源的介面之前幹這些事情。

也就是說,你現在有3個介面,比如一個使用者登入(/api/v1/login), 一個管理員列表(/api/v1/list),一個新增管理員資訊(/api/v1/add)。你現在的需求是查詢管理員列表與新增管理員介面需要token鑑權才能訪問,但是登入是不需要任何限制條件。

那麼你就可以在管理員列表和新增資訊介面之前加一箇中間件,使用router.use(中介軟體)即可。

可以看下我的

我的鑑權裡面是判斷tokan是否有效,無效的話我就直接返回400並且return了。我的意思是說鑑權失敗了那就return,不需要執行後續的list或者add介面。

但是。使用return壓根不起作用。postman模擬器請求的時候發現控制檯列印了錯誤資訊如下:

Headers were already written. Wanted to override status code 400 with 200

然後返回結果不僅僅有token鑑權不通過的400,竟然也把查詢結果給返回了。

這個結果很尷尬。

解決關鍵

中介軟體裡面有錯誤如果不想繼續後續介面的呼叫不能直接return,而是應該呼叫c.Abort()方法。

原始碼如下:

// Abort prevents pending handlers from being called. Note that this will not stop the current handler.
// Let's say you have an authorization middleware that validates that the current request is authorized.
// If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers
// for this request are not called.
func (c *Context) Abort() {
	c.index = abortIndex
}