github.com/System-Glitch/goyave/v2@v2.10.3-0.20200819142921-51011e75d504/native_handler.go (about)

     1  package goyave
     2  
     3  import (
     4  	"net/http"
     5  )
     6  
     7  // NativeMiddlewareFunc is a function which receives an http.Handler and returns another http.Handler.
     8  type NativeMiddlewareFunc func(http.Handler) http.Handler
     9  
    10  // NativeHandler is an adapter function for "http.Handler".
    11  // With this adapter, you can plug non-Goyave handlers to your application.
    12  //
    13  // Just remember that the body contains the raw data, which haven't been validated
    14  // nor converted. This means that native handlers are not guaranteed to work and
    15  // cannot modify the request data. Request properties, such as headers, can still
    16  // be modified.
    17  // Prefer implementing a Goyave handler.
    18  //
    19  // This feature is a compatibility layer with the rest of the Golang web ecosystem.
    20  // Prefer using Goyave handlers if possible.
    21  func NativeHandler(handler http.Handler) Handler {
    22  	return func(response *Response, request *Request) {
    23  		handler.ServeHTTP(response, request.httpRequest)
    24  	}
    25  }
    26  
    27  // NativeMiddleware is an adapter function for standard library middleware.
    28  //
    29  // Native middleware work like native handlers. See "NativeHandler" for more details.
    30  func NativeMiddleware(middleware NativeMiddlewareFunc) Middleware {
    31  	return func(next Handler) Handler {
    32  		return func(response *Response, request *Request) {
    33  			middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    34  				next(response, request)
    35  			})).ServeHTTP(response, request.httpRequest)
    36  		}
    37  	}
    38  }