github.com/thetreep/go-swagger@v0.0.0-20240223100711-35af64f14f01/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  	"log"
    10  	"net/http"
    11  	"os"
    12  	"path"
    13  
    14  	"github.com/go-openapi/errors"
    15  	"github.com/go-openapi/runtime"
    16  	"github.com/go-openapi/runtime/middleware"
    17  
    18  	"github.com/thetreep/go-swagger/examples/file-server/restapi/operations"
    19  	"github.com/thetreep/go-swagger/examples/file-server/restapi/operations/uploads"
    20  )
    21  
    22  //go:generate swagger generate server --target ../../file-server --name FileUpload --spec ../swagger.yml --principal interface{}
    23  
    24  func configureFlags(api *operations.FileUploadAPI) {
    25  	// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }
    26  }
    27  
    28  func configureAPI(api *operations.FileUploadAPI) 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.UseSwaggerUI()
    39  	// To continue using redoc as your UI, uncomment the following line
    40  	// api.UseRedoc()
    41  
    42  	api.JSONConsumer = runtime.JSONConsumer()
    43  	api.MultipartformConsumer = runtime.DiscardConsumer
    44  
    45  	api.JSONProducer = runtime.JSONProducer()
    46  
    47  	// You may change here the memory limit for this multipart form parser. Below is the default (32 MB).
    48  	// uploads.UploadFileMaxParseMemory = 32 << 20
    49  
    50  	uploadFolder, err := os.MkdirTemp(".", "upload")
    51  	if err != nil {
    52  		panic("could not create upload folder")
    53  	}
    54  	uploadCounter := 0
    55  
    56  	api.UploadsUploadFileHandler = uploads.UploadFileHandlerFunc(
    57  		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  
    92  	api.PreServerShutdown = func() {}
    93  
    94  	api.ServerShutdown = func() {}
    95  
    96  	return setupGlobalMiddleware(api.Serve(setupMiddlewares))
    97  }
    98  
    99  // The TLS configuration before HTTPS server starts.
   100  func configureTLS(tlsConfig *tls.Config) {
   101  	// Make all necessary changes to the TLS configuration here.
   102  }
   103  
   104  // As soon as server is initialized but not run yet, this function will be called.
   105  // If you need to modify a config, store server instance to stop it individually later, this is the place.
   106  // This function can be called multiple times, depending on the number of serving schemes.
   107  // scheme value will be set accordingly: "http", "https" or "unix".
   108  func configureServer(s *http.Server, scheme, addr string) {
   109  }
   110  
   111  // The middleware configuration is for the handler executors. These do not apply to the swagger.json document.
   112  // The middleware executes after routing but before authentication, binding and validation.
   113  func setupMiddlewares(handler http.Handler) http.Handler {
   114  	return handler
   115  }
   116  
   117  // The middleware configuration happens before anything, this middleware also applies to serving the swagger.json document.
   118  // So this is a good place to plug in a panic handling middleware, logging and metrics.
   119  func setupGlobalMiddleware(handler http.Handler) http.Handler {
   120  	return handler
   121  }