github.com/circl-dev/go-swagger@v0.31.0/examples/file-server/README.md (about)

     1  # File upload server
     2  
     3  This example demonstrates how to build a simple file upload endpoint
     4  with swagger and go-swagger.
     5  
     6  ## Try it
     7  
     8  1. Build the server
     9  
    10  ```
    11  cd restapi/cmd/file-upload-server
    12  go build
    13  
    14  ./file-upload-server --port 8000
    15  2021/01/17 18:54:09 Serving file upload at http://127.0.0.1:8000
    16  ```
    17  
    18  2. Run the client
    19  
    20  From another terminal:
    21  
    22  ```
    23  go run upload_file.go swagger.yml
    24  ```
    25  
    26  Logs on the server:
    27  ```
    28  2021/01/17 18:54:15 received file name: swagger.yml
    29  2021/01/17 18:54:15 received file size: 512
    30  2021/01/17 18:54:15 copied bytes 512
    31  2021/01/17 18:54:15 file uploaded copied as upload427417421/uploaded_file_0.dat
    32  ```
    33  
    34  The file has been copied in a temporary folder `cmd/file-upload-server/upload*/`
    35  
    36  
    37  ## Specification
    38  
    39  We use the swagger type `file` in a multipart form, like so:
    40  
    41  ```yaml
    42  paths:
    43    /upload:
    44      post:
    45        consumes:
    46        - multipart/form-data
    47        parameters:
    48        - name: file
    49          in: formData
    50          type: file
    51  ```
    52  
    53  ## Server side
    54  
    55  The handler receives a `io.ReadCloser` as the file to consume.
    56  
    57  Under the hood, the runtime builds this with a `*runtime.File`, which provides access to some header information, such as:
    58  
    59  ```go
    60  		if namedFile, ok := params.File.(*runtime.File); ok {
    61  			log.Printf("received file name: %s", namedFile.Header.Filename)
    62  			log.Printf("received file size: %d", namedFile.Header.Size)
    63  		}
    64  ```
    65  
    66  ## Client side
    67  
    68  The local file is handled as a `runtime.NamedReadCloser` (that is, a `io.ReadCloser` plus the `Name() string` method).
    69  A regular `os.File` satisfies this.
    70  
    71  The file can be passed directly to the client method, like so:
    72  
    73  ```go
    74  	params := uploads.NewUploadFileParams().WithFile(reader)
    75  
    76  	_, err := uploader.Uploads.UploadFile(params)
    77  ```