github.com/99MyCql/duffett@v0.1.0/app/data/realTimeData.go (about) 1 package data 2 3 import ( 4 "errors" 5 "io/ioutil" 6 "net/http" 7 "regexp" 8 "strconv" 9 "strings" 10 11 log "github.com/sirupsen/logrus" 12 13 "golang.org/x/text/encoding/simplifiedchinese" 14 ) 15 16 const sinaApi = "http://hq.sinajs.cn/list=" 17 18 // RealTimeData 股票实时数据 19 type RealTimeData struct { 20 StockCode string 21 StockName string 22 TodayOpeningPrice float64 23 YdayClosingPrice float64 24 CurPrice float64 25 TodayHighestPrice float64 26 TodayLowestPrice float64 27 TradedShareNum int64 28 Turnover float64 29 Date string 30 Time string 31 } 32 33 // GetRealTimeData 获取股票实时数据 34 func GetRealTimeData(tsCode string) (*RealTimeData, error) { 35 if len(tsCode) == 0 { 36 return nil, errors.New("tsCode 为空") 37 } 38 39 // 将 tushare 格式的 tsCode(000001.SZ) 替换成 sinaApi(sz000001) 接受的格式 40 var stockCode string 41 i := strings.Index(tsCode, ".") 42 if string(tsCode[len(tsCode)-1]) == "Z" { 43 stockCode = "sz" + string([]byte(tsCode)[0:i]) 44 } else if string(tsCode[len(tsCode)-1]) == "H" { 45 stockCode = "sh" + string([]byte(tsCode)[0:i]) 46 } else { 47 log.Error("未匹配的 tsCode") 48 return nil, errors.New("无法处理的 tsCode") 49 } 50 51 // 请求接口获取数据 52 rsp, err := http.Get(sinaApi + stockCode) 53 if err != nil { 54 log.Error(err) 55 return nil, err 56 } 57 body, err := ioutil.ReadAll(rsp.Body) 58 if err != nil { 59 log.Error(err) 60 return nil, err 61 } 62 63 // GBK转UTF-8 64 body, _ = simplifiedchinese.GBK.NewDecoder().Bytes(body) 65 strData := string(body) 66 log.Debug(strData) 67 68 // 从字符串中提取数据 69 r, _ := regexp.Compile("\".*?\"") 70 strData = strings.Trim(r.FindString(strData), "\"") 71 arrData := strings.Split(strData, ",") 72 log.Debug(arrData) 73 74 todayOpeningPrice, _ := strconv.ParseFloat(arrData[1], 64) 75 ydayClosingPrice, _ := strconv.ParseFloat(arrData[2], 64) 76 curPrice, _ := strconv.ParseFloat(arrData[3], 64) 77 todayHighestPrice, _ := strconv.ParseFloat(arrData[4], 64) 78 todayLowestPrice, _ := strconv.ParseFloat(arrData[5], 64) 79 tradedShareNum, _ := strconv.ParseInt(arrData[8], 10, 64) 80 turnover, _ := strconv.ParseFloat(arrData[9], 64) 81 return &RealTimeData{ 82 StockCode: stockCode, 83 StockName: arrData[0], 84 TodayOpeningPrice: todayOpeningPrice, 85 YdayClosingPrice: ydayClosingPrice, 86 CurPrice: curPrice, 87 TodayHighestPrice: todayHighestPrice, 88 TodayLowestPrice: todayLowestPrice, 89 TradedShareNum: tradedShareNum, 90 Turnover: turnover, 91 Date: arrData[30], 92 Time: arrData[31], 93 }, nil 94 }