You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
1.9 KiB

  1. // Copyright 2015 go-swagger maintainers
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package runtime
  15. import (
  16. "bytes"
  17. "encoding/csv"
  18. "errors"
  19. "io"
  20. )
  21. // CSVConsumer creates a new CSV consumer
  22. func CSVConsumer() Consumer {
  23. return ConsumerFunc(func(reader io.Reader, data interface{}) error {
  24. if reader == nil {
  25. return errors.New("CSVConsumer requires a reader")
  26. }
  27. csvReader := csv.NewReader(reader)
  28. writer, ok := data.(io.Writer)
  29. if !ok {
  30. return errors.New("data type must be io.Writer")
  31. }
  32. csvWriter := csv.NewWriter(writer)
  33. records, err := csvReader.ReadAll()
  34. if err != nil {
  35. return err
  36. }
  37. for _, r := range records {
  38. if err := csvWriter.Write(r); err != nil {
  39. return err
  40. }
  41. }
  42. csvWriter.Flush()
  43. return nil
  44. })
  45. }
  46. // CSVProducer creates a new CSV producer
  47. func CSVProducer() Producer {
  48. return ProducerFunc(func(writer io.Writer, data interface{}) error {
  49. if writer == nil {
  50. return errors.New("CSVProducer requires a writer")
  51. }
  52. dataBytes, ok := data.([]byte)
  53. if !ok {
  54. return errors.New("data type must be byte array")
  55. }
  56. csvReader := csv.NewReader(bytes.NewBuffer(dataBytes))
  57. records, err := csvReader.ReadAll()
  58. if err != nil {
  59. return err
  60. }
  61. csvWriter := csv.NewWriter(writer)
  62. for _, r := range records {
  63. if err := csvWriter.Write(r); err != nil {
  64. return err
  65. }
  66. }
  67. csvWriter.Flush()
  68. return nil
  69. })
  70. }