Example #1
0
// HandleDelivery handles the amqp.Delivery object and either prints it out or
// writes it to a files
func HandleDelivery(delivery amqp.Delivery, debugger amqptools.Debugger) {
	addlData := make(map[string]interface{})
	addlData["BodyAsString"] = string(delivery.Body)
	deliveryPlus := &amqptools.DeliveryPlus{
		delivery,
		addlData,
	}

	var jsonBytes []byte
	var err error

	// necessary because otherwise it isn't unmarshalable
	deliveryPlus.RawDelivery.Acknowledger = nil

	if *prettyPrint {
		jsonBytes, err = json.MarshalIndent(deliveryPlus, "", "\t")
		if debugger.WithError(err, "Unable to marshal delivery into JSON.") {
			return
		}
	} else {
		jsonBytes, err = json.Marshal(deliveryPlus)
		if debugger.WithError(err, "Unable to marshal delivery into JSON.") {
			return
		}
	}

	if len(*outDirFlag) == 0 {
		fmt.Println(fmt.Sprintf("%s", string(jsonBytes)))
	} else {
		var folderName string
		if len(delivery.MessageId) > 0 {
			folderName = delivery.MessageId
		} else {
			h := sha1.New()
			fmt.Fprintf(h, "%s", jsonBytes)
			folderName = fmt.Sprintf("%x", h.Sum(nil))
		}

		var exchangeStr string
		if len(delivery.Exchange) == 0 {
			exchangeStr = "_"
		} else {
			exchangeStr = delivery.Exchange
		}

		pathParts := []string{
			strings.TrimRight(*outDirFlag, string(os.PathSeparator)),
			exchangeStr,
			folderName,
		}
		fullPath := strings.Join(pathParts, string(os.PathSeparator))

		fileName := fmt.Sprintf("%s%smessage.json", fullPath, string(os.PathSeparator))

		err = os.MkdirAll(fullPath, os.ModeDir|os.ModePerm)
		if debugger.WithError(err, fmt.Sprintf("Unable to create output directory '%s'.", fullPath)) {
			return
		}

		file, err := os.Create(fileName)
		if debugger.WithError(err, fmt.Sprintf("Unable to create file '%s'.", fileName)) {
			return
		}

		_, err = file.Write(jsonBytes)
		if debugger.WithError(err, fmt.Sprintf("Unable to write data into buffer for '%s'.", fileName)) {
			return
		}
		debugger.Print(fmt.Sprintf("Data written to %s", fileName))

		err = file.Close()
		debugger.WithError(err, fmt.Sprintf("Unable to close file '%s'.", fileName))
	}

	if *keepMessages {
		err = delivery.Reject(true)
	} else {
		err = delivery.Ack(false)
	}
	if debugger.WithError(err, "Unable to Ack a message") {
		return
	}
}