github.com/kaisawind/go-swagger@v0.19.0/examples/oauth2/restapi/configure_oauth_sample.go (about)

     1  // This file is safe to edit. Once it exists it will not be overwritten
     2  
     3  package restapi
     4  
     5  import (
     6  	"context"
     7  	"crypto/tls"
     8  	"log"
     9  	"net/http"
    10  
    11  	errors "github.com/go-openapi/errors"
    12  	runtime "github.com/go-openapi/runtime"
    13  	middleware "github.com/go-openapi/runtime/middleware"
    14  	"github.com/go-openapi/swag"
    15  
    16  	"github.com/go-swagger/go-swagger/examples/oauth2/restapi/operations"
    17  	"github.com/go-swagger/go-swagger/examples/oauth2/restapi/operations/customers"
    18  
    19  	models "github.com/go-swagger/go-swagger/examples/oauth2/models"
    20  )
    21  
    22  //go:generate swagger generate server --target .. --name oauthSample --spec ../swagger.yml --principal models.Principal
    23  
    24  func configureFlags(api *operations.OauthSampleAPI) {
    25  	// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }
    26  }
    27  
    28  func configureAPI(api *operations.OauthSampleAPI) http.Handler {
    29  	// configure the api here
    30  	api.ServeError = errors.ServeError
    31  
    32  	// Set your custom logger if needed. Default one is log.Printf
    33  	// Expected interface func(string, ...interface{})
    34  	//
    35  	// Example:
    36  	api.Logger = log.Printf
    37  
    38  	api.JSONConsumer = runtime.JSONConsumer()
    39  
    40  	api.JSONProducer = runtime.JSONProducer()
    41  
    42  	api.OauthSecurityAuth = func(token string, scopes []string) (*models.Principal, error) {
    43  		ok, err := authenticated(token)
    44  		if err != nil {
    45  			return nil, errors.New(401, "error authenticate")
    46  		}
    47  		if !ok {
    48  			return nil, errors.New(401, "invalid token")
    49  		}
    50  		prin := models.Principal(token)
    51  		return &prin, nil
    52  
    53  	}
    54  
    55  	// Set your custom authorizer if needed. Default one is security.Authorized()
    56  	// Expected interface runtime.Authorizer
    57  	//
    58  	// Example:
    59  	// api.APIAuthorizer = security.Authorized()
    60  	api.GetAuthCallbackHandler = operations.GetAuthCallbackHandlerFunc(func(params operations.GetAuthCallbackParams) middleware.Responder {
    61  		token, err := callback(params.HTTPRequest)
    62  		if err != nil {
    63  			return middleware.NotImplemented("operation .GetAuthCallback error")
    64  		}
    65  		log.Println("Token", token)
    66  		return operations.NewGetAuthCallbackDefault(500).WithPayload(&models.Error{Code: 500, Message: swag.String(token)})
    67  	})
    68  	api.GetLoginHandler = operations.GetLoginHandlerFunc(func(params operations.GetLoginParams) middleware.Responder {
    69  		return login(params.HTTPRequest)
    70  	})
    71  	api.CustomersCreateHandler = customers.CreateHandlerFunc(func(params customers.CreateParams, principal *models.Principal) middleware.Responder {
    72  		return middleware.NotImplemented("operation customers.Create has not yet been implemented")
    73  	})
    74  	api.CustomersGetIDHandler = customers.GetIDHandlerFunc(func(params customers.GetIDParams, principal *models.Principal) middleware.Responder {
    75  		log.Println("hit customer API")
    76  		return middleware.NotImplemented("operation customers.GetID has not yet been implemented")
    77  	})
    78  
    79  	api.ServerShutdown = func() {}
    80  
    81  	return setupGlobalMiddleware(api.Serve(setupMiddlewares))
    82  }
    83  
    84  // The TLS configuration before HTTPS server starts.
    85  func configureTLS(tlsConfig *tls.Config) {
    86  	// Make all necessary changes to the TLS configuration here.
    87  }
    88  
    89  // As soon as server is initialized but not run yet, this function will be called.
    90  // If you need to modify a config, store server instance to stop it individually later, this is the place.
    91  // This function can be called multiple times, depending on the number of serving schemes.
    92  // scheme value will be set accordingly: "http", "https" or "unix"
    93  func configureServer(s *http.Server, scheme, addr string) {
    94  }
    95  
    96  // This demonstrates how to enrich and pass custom context keys.
    97  // In this case, we cache the current responseWriter in context.
    98  type customContextKey int8
    99  
   100  const (
   101  	_ customContextKey = iota
   102  	ctxResponseWriter
   103  )
   104  
   105  // The middleware configuration is for the handler executors. These do not apply to the swagger.json document.
   106  // The middleware executes after routing but before authentication, binding and validation
   107  func setupMiddlewares(handler http.Handler) http.Handler {
   108  	ourFunc := func(w http.ResponseWriter, r *http.Request) {
   109  		rctx := context.WithValue(r.Context(), ctxResponseWriter, w)
   110  		handler.ServeHTTP(w, r.WithContext(rctx))
   111  	}
   112  	return http.HandlerFunc(ourFunc)
   113  
   114  }
   115  
   116  // The middleware configuration happens before anything, this middleware also applies to serving the swagger.json document.
   117  // So this is a good place to plug in a panic handling middleware, logging and metrics
   118  func setupGlobalMiddleware(handler http.Handler) http.Handler {
   119  	return handler
   120  }