flexible_go.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright (c) 2014 Couchbase, Inc.
  2. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
  3. // except in compliance with the License. You may obtain a copy of the License at
  4. // http://www.apache.org/licenses/LICENSE-2.0
  5. // Unless required by applicable law or agreed to in writing, software distributed under the
  6. // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  7. // either express or implied. See the License for the specific language governing permissions
  8. // and limitations under the License.
  9. package flexible_go
  10. import (
  11. "fmt"
  12. "time"
  13. "github.com/couchbaselabs/bleve/analysis"
  14. "github.com/couchbaselabs/bleve/registry"
  15. )
  16. const Name = "flexiblego"
  17. type FlexibleGoDateTimeParser struct {
  18. layouts []string
  19. }
  20. func NewFlexibleGoDateTimeParser(layouts []string) *FlexibleGoDateTimeParser {
  21. return &FlexibleGoDateTimeParser{
  22. layouts: layouts,
  23. }
  24. }
  25. func (p *FlexibleGoDateTimeParser) ParseDateTime(input string) (time.Time, error) {
  26. for _, layout := range p.layouts {
  27. rv, err := time.Parse(layout, input)
  28. if err == nil {
  29. return rv, nil
  30. }
  31. }
  32. return time.Time{}, analysis.INVALID_DATETIME
  33. }
  34. func FlexibleGoDateTimeParserConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.DateTimeParser, error) {
  35. layouts, ok := config["layouts"].([]interface{})
  36. if !ok {
  37. return nil, fmt.Errorf("must specify layouts")
  38. }
  39. layoutStrs := make([]string, 0)
  40. for _, layout := range layouts {
  41. layoutStr, ok := layout.(string)
  42. if ok {
  43. layoutStrs = append(layoutStrs, layoutStr)
  44. }
  45. }
  46. return NewFlexibleGoDateTimeParser(layoutStrs), nil
  47. }
  48. func init() {
  49. registry.RegisterDateTimeParser(Name, FlexibleGoDateTimeParserConstructor)
  50. }