Skip to content

Instantly share code, notes, and snippets.

@ninedraft
Created July 17, 2020 08:40
Show Gist options
  • Save ninedraft/61724ebc56ae1a712f39eed0932cc95c to your computer and use it in GitHub Desktop.
Save ninedraft/61724ebc56ae1a712f39eed0932cc95c to your computer and use it in GitHub Desktop.
Golang STD HTTP to gin middleware adapter
// Copyright 2020 Petrukhin Pavel
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package asgin
import (
"net/http"
"github.com/gin-gonic/gin"
)
// AsGin converts middleware to the gin middleware handler.
func AsGin(middleware func(next http.Handler) http.Handler) gin.HandlerFunc {
return func(gctx *gin.Context) {
var skip = true
var handler http.HandlerFunc = func(http.ResponseWriter, *http.Request) {
skip = false
}
middleware(handler).ServeHTTP(gctx.Writer, gctx.Request)
switch {
case skip:
gctx.Abort()
default:
gctx.Next()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment