1

I am using go-swagger to create API endpoint and the business logic is called inside the handler function directly , which is working fine . I need to implement "Middleware" , which can also ease in unit testing which I am doing using mockery and testify . Below is the code .

Swagger.yml

I have provided only sample code for endpoint

---
swagger: "2.0"
info:
  description: Swagger api for VM Manager
  title: vmManager
  version: 1.0.0
consumes:
- application/json
produces:
- application/json
schemes:
- http
paths:
  /createVM:
    post:
      tags:
        - vmManager
      operationId: createVM
      parameters:
        - name: body
          in: body
          schema:
            $ref: "#/definitions/vmInput"
      responses:
        201:
          description: Created
          schema:
            $ref: "#/definitions/response"
        default:
          description: error
          schema:
            $ref: "#/definitions/errorObject"

configure_vmmanager.go

Call from above swagger comes here

api.VMManagerCreateVMHandler = vm_manager.CreateVMHandlerFunc(func(params vm_manager.CreateVMParams) middleware.Responder {
        log.Debugf("Create VM Handler Called")
        log.Infof("Payload Data : %v , VM Name : %v , Request ID : %v", params.Body.ConfigData, params.Body.VMName, params.Body.RequestID)  
        log.WithFields(log.Fields{
            "Request Payload": params.Body,
        }).Infof("Request Payload to  CreateVMHandler: ")

        vmOutput, err := resthandler.CreateVMHandler(params.Body)
        if err != nil {
                log.Errorf("Eror while creating VM %v :" ,err)
                 errorObject := &models.ErrorObject{ErrorDetails: err ,}
    // TODO Addition for custom error code
                //return vm_manager.NewCreateVMDefault(*ErrorCode).WithPayload(&models.Error{ErrorCode: errorCode, ErrorDesc: err.ErrorDesc})
                return vm_manager.NewCreateVMDefault(int(*err.ErrorCode)).WithPayload(errorObject)
        }
        log.WithFields(log.Fields{
            "Response of CreateVMHandler":vmOutput,
        }).Infof("Response from  CreateVMHandler :")
        return vm_manager.NewCreateVMCreated().WithPayload(vmOutput)
    })

create_vm_handler.go

Definition part

func CreateVMHandler(item *models.VMInput) (*models.Response, *models.ErrorDetails) {
.
.
.
return serverOut, nil
}

Please comment in case of any additional information is needed.

Markus W Mahlberg
  • 19,711
  • 6
  • 65
  • 89
infiniteLearner
  • 3,555
  • 2
  • 23
  • 32

0 Answers0