simple.go 962 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package temperature
  2. import (
  3. "bufio"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. )
  8. type simpleParser struct {
  9. reader *bufio.Reader
  10. }
  11. // NewSimpleParser returns a parser that scans for temperature: 53 C
  12. func NewSimpleParser(reader *bufio.Reader) Parser {
  13. return &simpleParser{reader: reader}
  14. }
  15. // Measure returns the temperature. Null if it can't
  16. func (sp simpleParser) Measure() (*Measurement, error) {
  17. text, err := sp.reader.ReadString('\n')
  18. if err != nil {
  19. return nil, err
  20. }
  21. fields := strings.Fields(text)
  22. for i := 0; i < len(fields); i++ {
  23. fields[i] = strings.ToLower(fields[i])
  24. }
  25. if len(fields) == 3 {
  26. if strings.Compare(fields[0], "temperature:") == 0 {
  27. temp, _ := strconv.ParseFloat(fields[1], 64)
  28. unit := fields[2]
  29. if strings.Compare(unit, "f") == 0 {
  30. temp = (temp - 32) * (5.0 / 9.0)
  31. }
  32. fmt.Println("temp is " + strconv.FormatFloat(temp, 'f', 6, 64))
  33. return &Measurement{ID: 0, Temperature: temp}, nil
  34. }
  35. }
  36. return nil, nil
  37. }