generated from VLADIMIR/template
add parser
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
package data_parser
|
||||
|
||||
import "context"
|
||||
|
||||
type IDataParser interface {
|
||||
Parse(ctx context.Context, url string, v interface{}) error
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package data_parser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
"github.com/gocarina/gocsv"
|
||||
)
|
||||
|
||||
type parser struct{}
|
||||
|
||||
func NewGoogleTableScheduleParser() IDataParser {
|
||||
return &parser{}
|
||||
}
|
||||
|
||||
func (p *parser) Parse(_ context.Context, url string, v interface{}) error {
|
||||
re := regexp.MustCompile(`/d/([a-zA-Z0-9-_]+)`)
|
||||
matches := re.FindStringSubmatch(url)
|
||||
if len(matches) < 2 {
|
||||
return fmt.Errorf("Не удалось найти ID таблицы в ссылке")
|
||||
}
|
||||
sheetID := matches[1]
|
||||
|
||||
csvURL := fmt.Sprintf("https://docs.google.com/spreadsheets/d/%s/export?format=csv", sheetID)
|
||||
|
||||
resp, err := http.Get(csvURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Ошибка при скачивании таблицы: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("Ошибка: статус код %d (убедитесь, что таблица публичная)", resp.StatusCode)
|
||||
}
|
||||
|
||||
if err := gocsv.Unmarshal(resp.Body, v); err != nil {
|
||||
return fmt.Errorf("Ошибка при парсинге CSV в структуру: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user