github.com/circl-dev/go-swagger@v0.31.0/examples/file-server/restapi/configure_file_upload.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  	"crypto/tls"
     7  	"fmt"
     8  	"io"
     9  	"io/ioutil"
    10  	"log"
    11  	"net/http"
    12  	"os"
    13  	"path"
    14  
    15  	"github.com/circl-dev/runtime"
    16  	"github.com/circl-dev/runtime/middleware"
    17  	"github.com/go-openapi/errors"
    18  
    19  	"github.com/circl-dev/go-swagger/examples/file-server/restapi/operations"
    20  	"github.com/circl-dev/go-swagger/examples/file-server/restapi/operations/uploads"
    21  )
    22  
    23  //go:generate swagger generate server --target ../../file-server --name FileUpload --spec ../swagger.yml --principal interface{}
    24  
    25  func configureFlags(api *operations.FileUploadAPI) {
    26  	// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }
    27  }
    28  
    29  func configureAPI(api *operations.FileUploadAPI) http.Handler {
    30  	// configure the api here
    31  	api.ServeError = errors.ServeError
    32  
    33  	// Set your custom logger if needed. Default one is log.Printf
    34  	// Expected interface func(string, ...interface{})
    35  	//
    36  	// Example:
    37  	// api.Logger = log.Printf
    38  
    39  	api.UseSwaggerUI()
    40  	// To continue using redoc as your UI, uncomment the following line
    41  	// api.UseRedoc()
    42  
    43  	api.JSONConsumer = runtime.JSONConsumer()
    44  	api.MultipartformConsumer = runtime.DiscardConsumer
    45  
    46  	api.JSONProducer = runtime.JSONProducer()
    47  
    48  	// You may change here the memory limit for this multipart form parser. Below is the default (32 MB).
    49  	// uploads.UploadFileMaxParseMemory = 32 << 20
    50  
    51  	uploadFolder, err := ioutil.TempDir(".", "upload")
    52  	if err != nil {
    53  		panic("could not create upload folder")
    54  	}
    55  	uploadCounter := 0
    56  
    57  	api.UploadsUploadFileHandler = uploads.UploadFileHandlerFunc(func(params uploads.UploadFileParams) middleware.Responder {
    58  
    59  		if params.File == nil {
    60  			return middleware.Error(404, fmt.Errorf("no file provided"))
    61  		}
    62  		defer func() {
    63  			_ = params.File.Close()
    64  		}()
    65  
    66  		if namedFile, ok := params.File.(*runtime.File); ok {
    67  			log.Printf("received file name: %s", namedFile.Header.Filename)
    68  			log.Printf("received file size: %d", namedFile.Header.Size)
    69  		}
    70  
    71  		// uploads file and save it locally
    72  		filename := path.Join(uploadFolder, fmt.Sprintf("uploaded_file_%d.dat", uploadCounter))
    73  		uploadCounter++
    74  		f, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
    75  		if err != nil {
    76  			return middleware.Error(500, fmt.Errorf("could not create file on server"))
    77  		}
    78  
    79  		n, err := io.Copy(f, params.File)
    80  		if err != nil {
    81  			return middleware.Error(500, fmt.Errorf("could not upload file on server"))
    82  		}
    83  
    84  		log.Printf("copied bytes %d", n)
    85  
    86  		log.Printf("file uploaded copied as %s", filename)
    87  
    88  		return uploads.NewUploadFileOK()
    89  	})
    90  
    91  	api.PreServerShutdown = func() {}
    92  
    93  	api.ServerShutdown = func() {}
    94  
    95  	return setupGlobalMiddleware(api.Serve(setupMiddlewares))
    96  }
    97  
    98  // The TLS configuration before HTTPS server starts.
    99  func configureTLS(tlsConfig *tls.Config) {
   100  	// Make all necessary changes to the TLS configuration here.
   101  }
   102  
   103  // As soon as server is initialized but not run yet, this function will be called.
   104  // If you need to modify a config, store server instance to stop it individually later, this is the place.
   105  // This function can be called multiple times, depending on the number of serving schemes.
   106  // scheme value will be set accordingly: "http", "https" or "unix".
   107  func configureServer(s *http.Server, scheme, addr string) {
   108  }
   109  
   110  // The middleware configuration is for the handler executors. These do not apply to the swagger.json document.
   111  // The middleware executes after routing but before authentication, binding and validation.
   112  func setupMiddlewares(handler http.Handler) http.Handler {
   113  	return handler
   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  }