Commit 1520bfd5 authored by 吴贤德's avatar 吴贤德

Services

parent 8ade52ae
package Common
import (
"fmt"
"src/Common/DateTime"
"testing"
)
//func Test_ValidMobile(t *testing.T) {
// m1 := "13552480004"
// if Validation.ValidMobile(m1) {
// fmt.Println(m1, "是手机号")
// }
// m2 := "17712588258"
// if Validation.ValidMobile(m2) {
// fmt.Println(m2, "是手机号")
// }
// m3 := "27712588258"
// if Validation.ValidMobile(m3) {
// fmt.Println(m3, "是手机号")
// } else {
// fmt.Println(m3, "不是手机号")
// }
//
// fmt.Println("hour:", time.Now().Hour())
//}
//
//func Test_GetTimestampOfNano(t *testing.T) {
// fmt.Printf("时间戳(秒):%v;\n", time.Now().Unix())
// fmt.Printf("时间戳(纳秒):%v;\n", time.Now().UnixNano())
// fmt.Printf("时间戳(毫秒):%v;\n", time.Now().UnixNano()/1e6)
// fmt.Printf("时间戳(纳秒转换为秒):%v;\n", time.Now().UnixNano()/1e9)
//}
//
//func Test_Download(t *testing.T) {
// url := "http://tsn.baidu.com/text2audio?lan=zh&ctp=1&cuid=abcdxxxx&tok=24.f8a7e949598695590b7e49fe741ecbb4.2592000.1537601050.282335-11675489&tex=%25E6%25B2%25B3%25E5%258D%2597%25E8%25B7%25AF%25EF%25BC%259A%25E6%25A0%2588%25E6%25A1%25A5%25E5%2585%25AC%25E5%259B%25AD%25E9%2599%2584%25E8%25BF%2591%25E8%2587%25AA%25E5%258D%2597%25E5%2590%2591%25E5%258C%2597%25E4%25B8%25A5%25E9%2587%258D%25E6%258B%25A5%25E5%25A0%25B5%25EF%25BC%259B%25E9%259D%2592%25E5%25B2%259B%25E8%2583%25B6%25E5%25B7%259E%25E6%25B9%25BE%25E9%259A%25A7%25E9%2581%2593%25EF%25BC%259A%25E4%25BB%258E%25E9%259D%2592%25E5%25B2%259B%25E8%2583%25B6%25E5%25B7%259E%25E6%25B9%25BE%25E9%259A%25A7%25E9%2581%2593%25E5%2587%25BA%25E5%258F%25A3%25E5%2588%25B0%25E4%25BA%2591%25E5%258D%2597%25E8%25B7%25AF%25E5%2587%25BA%25E5%258F%25A3%25E8%25A1%258C%25E9%25A9%25B6%25E7%25BC%2593%25E6%2585%25A2%25E3%2580%2582&vol=15&per=1&spd=5&pit=5&aue=3"
// r, _ := req.Get(url)
// filename := "./download/1.mp3"
// err := r.ToFile(filename)
// if err != nil {
// fmt.Println("download err:", err)
// }
//}
func Test_fmtdate(t *testing.T) {
strTime:="2019-07-01 12:00:00"
time,err:=DateTime.ParseDateTime(strTime)
if err==nil {
str:=DateTime.Format("YYYYMMDDhhmmss",time)
fmt.Println(strTime,"-->",str)
}
}
\ No newline at end of file
package Crypto
import (
"crypto/md5"
"encoding/hex"
)
//生成32位md5字串
func GetMd5String(s string) string {
h := md5.New()
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
}
package DateTime
import (
"strings"
"time"
)
/*
DateTime provides a date formatter and parser using the syntax of Microsoft Excel (TM).
Additionally it offers default conversions for date time and datetime.
Why?
Microsoft Excel (TM) has a well known syntax for date formatting, that more
memorable than the syntax chosen in the time package in the go library.
Usage
date := DateTime.Format("DD.MM.YYYY", time.Now())
fmt.Println(date)
var err
date, err = DateTime.Parse("M/D/YY", "2/3/07")
fmt.Println(date, err)
*/
/*
Formats:
M - month (1)
MM - month (01)
MMM - month (Jan)
MMMM - month (January)
D - day (2)
DD - day (02)
DDD - day (Mon)
DDDD - day (Monday)
YY - year (06)
YYYY - year (2006)
hh - hours (15)
mm - minutes (04)
ss - seconds (05)
AM/PM hours: 'h' followed by optional 'mm' and 'ss' followed by 'pm', e.g.
hpm - hours (03PM)
h:mmpm - hours:minutes (03:04PM)
h:mm:sspm - hours:minutes:seconds (03:04:05PM)
Time zones: a time format followed by 'ZZZZ', 'ZZZ' or 'ZZ', e.g.
hh:mm:ss ZZZZ (16:05:06 +0100)
hh:mm:ss ZZZ (16:05:06 CET)
hh:mm:ss ZZ (16:05:06 +01:00)
*/
func replace(in string) (out string) {
out = in
for _, ph := range Placeholder {
out = strings.Replace(out, ph.find, ph.subst, -1)
}
return
}
// Format formats a date based on Microsoft Excel (TM) conventions
func Format(format string, date time.Time) string {
if format == "" {
format = DefaultDateTimeFormat
}
return date.Format(replace(format))
}
// Parse parses a value to a date based on Microsoft Excel (TM) formats
func Parse(format string, value string) (time.Time, error) {
if format == "" {
format = DefaultDateTimeFormat
}
return time.Parse(replace(format), value)
}
type p struct{ find, subst string }
var Placeholder = []p{
{"hh", "15"},
{"h", "03"},
{"mm", "04"},
{"ss", "05"},
{"MMMM", "January"},
{"MMM", "Jan"},
{"MM", "01"},
{"M", "1"},
{"pm", "PM"},
{"ZZZZ", "-0700"},
{"ZZZ", "MST"},
{"ZZ", "Z07:00"},
{"YYYY", "2006"},
{"YY", "06"},
{"DDDD", "Monday"},
{"DDD", "Mon"},
{"DD", "02"},
{"D", "2"},
}
var (
DefaultTimeFormat = "hh:mm:ss"
DefaultDateFormat = "YYYY-MM-DD"
DefaultDateTimeFormat = "YYYY-MM-DD hh:mm:ss"
)
// FormatDate formats the given date to the DefaultDateFormat
func FormatDate(date time.Time) string {
return Format(DefaultDateFormat, date)
}
// FormatTime formats the given date to the DefaultTimeFormat
func FormatTime(date time.Time) string {
return Format(DefaultTimeFormat, date)
}
// FormatTime formats the given date to the DefaultDateTimeFormat
func FormatDateTime(date time.Time) string {
return Format(DefaultDateTimeFormat, date)
}
// Parse parses a date in DefaultDateFormat to a date
func ParseDate(value string) (time.Time, error) {
return Parse(DefaultDateFormat, value)
}
// Parse parses a date in DefaultTimeFormat to a date
func ParseTime(value string) (time.Time, error) {
return Parse(DefaultTimeFormat, value)
}
// Parse parses a date in DefaultDateTimeFormat to a date
func ParseDateTime(value string) (time.Time, error) {
return Parse(DefaultDateTimeFormat, value)
}
package File
import (
"os"
)
/*
判断文件或文件夹是否存在
如果返回的错误为nil,说明文件或文件夹存在
如果返回的错误类型使用os.IsNotExist()判断为true,说明文件或文件夹不存在
如果返回的错误为其它类型,则不确定是否在存在
*/
func PathExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
//创建目录
func MakeDir(dir string) (bool, error) {
b, err := PathExists(dir)
if !b {
err = os.MkdirAll(dir, os.ModePerm)
if err == nil {
b = true
}
}
return b, err
}
//写文件
func WriteFile(filename string, content string) error {
file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0766) //以读写方式打开文件,如果不存在,则创建
defer file.Close()
if err != nil {
return err
}
file.WriteString(content)
return nil
}
package Math
import (
"fmt"
"math"
"math/rand"
"strconv"
"time"
)
func Round(f float64, n int) float64 {
n10 := math.Pow10(n)
return math.Trunc((f+0.5/n10)*n10) / n10
}
func Round2(f float64, n int) float64 {
floatStr := fmt.Sprintf("%."+strconv.Itoa(n)+"f", f)
inst, _ := strconv.ParseFloat(floatStr, 64)
return inst
}
// 函 数:生成随机数
// 概 要:
// 参 数:
// min: 最小值
// max: 最大值
// 返回值:
// int64: 生成的随机数
func RandInt64(min, max int64) int64 {
rand.Seed(time.Now().UnixNano())
if min >= max || min == 0 || max == 0 {
return max
}
return rand.Int63n(max-min) + min
}
package Request
import (
"github.com/imroc/req"
log "github.com/sirupsen/logrus"
"time"
)
type Request struct {
}
func init() {
req.Debug =false
}
//post request
func Post(url string, jsonBody string) (string, error) {
//log.Infof("request: %s, post:%s \n",url,jsonBody)
//req.Debug = true
req.SetFlags(req.LstdFlags | req.Lcost)
req.SetTimeout(time.Duration(60) * time.Second)
authHeader := req.Header{
"Content-Type": "application/json;charset=utf-8",
"Accept": "application/json",
// "Authorization": auth,
}
r, err := req.Post(url, authHeader, jsonBody)
// fmt.Printf("resp: %+v", r)
if err != nil {
//fmt.Println("query err:", err, " url:", url, " json:", jsonBody)
log.Errorln("query err:", err, " url:", url, " json:", jsonBody)
return "", err
} else {
return r.String(), err
}
}
func Get(url string) (string, error) {
//log.Infoln("request : ",url)
//req.Debug = false
req.SetFlags(req.LstdFlags | req.Lcost)
req.SetTimeout(time.Duration(60) * time.Second)
authHeader := req.Header{
"Content-Type": "application/json;charset=utf-8",
"Accept": "application/json",
// "Authorization": auth,
}
r, err := req.Get(url, authHeader)
// fmt.Printf("resp: %+v", r)
if err != nil {
//fmt.Println("query err:", err, " url:", url)
log.Errorln("query err:", err, " url:", url)
return "", err
} else {
return r.String(), err
}
}
package Unit
import (
"strconv"
)
//将 1m/1h/1d 转换成秒
func Time2Seconds(str string) int {
seconds, err := strconv.Atoi(str)
if err != nil { //转换失败
rs := []rune(str)
lth := len(rs)
sNum := string(rs[0 : lth-1]) //数值
sUnit := string(rs[lth-1 : lth]) //单位:s-秒,m-分钟,h-小时,d-天
n, err1 := strconv.Atoi(sNum)
if err1 == nil {
switch sUnit {
case "s":
seconds = n
break
case "m":
seconds = n * 60
break
case "h":
seconds = n * 3600
break
case "d":
seconds = n * 3600 * 24
break
default:
seconds = 3600 * 24
break
}
} else {
seconds = 60 //
}
}
//ret := strconv.Itoa(seconds)
// fmt.Println("Time2Seconds : ", str, " --> ", ret)
return seconds
}
package Validation
import (
"errors"
"regexp"
"src/Common/Crypto"
"strconv"
"time"
)
//sign校验
func ValidSign(tm string, spcode string, sign string, Sps map[string]string) error {
// return nil //测试时不校验
var err error
if len(tm) > 0 && len(spcode) > 0 && len(sign) > 0 {
key := Sps[spcode]
if len(key) > 0 {
t, err1 := strconv.ParseInt(tm, 10, 64)
if err1 != nil {
err = err1
} else {
span := time.Now().Unix() - t
if span > 600 {
err = errors.New("请求超时")
} else {
mySign := Crypto.GetMd5String(tm + key + spcode)
if mySign != sign {
err = errors.New("sign不匹配")
}
}
}
} else {
err = errors.New("sp不存在")
}
} else {
err = errors.New("校验参数不完整")
}
return err
}
//验证是否为手机号
func ValidMobile(mobileNum string) bool {
// reg := `^1([38][0-9]|14[57]|5[^4])\d{8}$`
reg := `^[1][3,4,5,7,8][0-9]{9}$`
rgx := regexp.MustCompile(reg)
return rgx.MatchString(mobileNum)
}
package Config
import (
"github.com/bitly/go-simplejson"
cmap "github.com/orcaman/concurrent-map"
"src/Common/Request"
"sync"
"time"
)
type Config struct {
Ini map[string]string //Ini配置
Sys cmap.ConcurrentMap //Sys配置
Sps cmap.ConcurrentMap //Sp配置
}
var config *Config
var once sync.Once
func GetInstance() *Config {
once.Do(func() {
config = new(Config)
config.Ini = initIniConfig("./", "config.ini", "debug")
initLogConfig(config.Ini["log_path"], config.Ini["log_filename"], 24*30*time.Hour, 1*time.Hour)
config.Sys = cmap.New()
config.Sps = cmap.New()
})
return config
}
func (this *Config) InitSysConfig() error {
url := this.Ini["api_conf_sys"]
var data string = ""
var err error
data, err = Request.Get(url)
if err == nil {
jsonObj, err1 := simplejson.NewJson([]byte(data))
if err1 != nil {
err = err1
} else {
sysConf, err2 := jsonObj.Map()
if err2 != nil {
err = err2
} else {
for k, v := range sysConf {
//log.Infoln(k, v)
this.Sys.Set(k, v)
}
}
}
}
return err
}
func (this *Config) InitSpsConfig() error {
url := this.Ini["api_conf_sps"]
var data string = ""
var err error
data, err = Request.Get(url)
if err == nil {
jsonObj, err1 := simplejson.NewJson([]byte(data))
if err1 != nil {
err = err1
} else {
spsConf, err2 := jsonObj.Map()
if err2 != nil {
err = err2
} else {
for k, v := range spsConf {
//log.Infoln(k, v)
this.Sps.Set(k, v)
}
}
}
}
return err
}
package Config
import (
"fmt"
"testing"
)
func TestConfig_InitSpsConfig(t *testing.T) {
config:=GetInstance()
config.InitSpsConfig()
fmt.Printf("%+v",config.Sps)
}
\ No newline at end of file
package Config
import (
"flag"
iniReader "github.com/larspensjo/config"
log "github.com/sirupsen/logrus"
"runtime"
)
func initIniConfig(dir string, configName string, topic string) map[string]string {
var (
configFile = flag.String(dir, configName, "General configuration file")
)
var TOPIC = make(map[string]string)
runtime.GOMAXPROCS(runtime.NumCPU())
flag.Parse()
cfg, err := iniReader.ReadDefault(*configFile)
if err != nil {
log.Fatal("Fail to find", *configFile, err)
}
if cfg.HasSection(topic) {
section, err := cfg.SectionOptions(topic)
if err == nil {
for _, v := range section {
options, err := cfg.String(topic, v)
if err == nil {
TOPIC[v] = options
}
}
}
}
log.Infoln(TOPIC)
return TOPIC
}
package Config
import (
rotatelogs "github.com/lestrrat/go-file-rotatelogs"
"github.com/pkg/errors"
"github.com/rifflock/lfshook"
log "github.com/sirupsen/logrus"
"path"
"time"
)
// config logrus log to local filesystem, with file rotation
func initLogConfig(logPath string, logFileName string, maxAge time.Duration, rotationTime time.Duration) {
baseLogPaht := path.Join(logPath, logFileName)
writer, err := rotatelogs.New(
baseLogPaht+".%Y%m%d%H%M",
rotatelogs.WithLinkName(baseLogPaht), // 生成软链,指向最新日志文件
rotatelogs.WithMaxAge(maxAge), // 文件最大保存时间
rotatelogs.WithRotationTime(rotationTime), // 日志切割时间间隔
)
if err != nil {
log.Errorf("config local file system logger error. %+v", errors.WithStack(err))
}
lfHook := lfshook.NewHook(lfshook.WriterMap{
log.DebugLevel: writer, // 为不同级别设置不同的输出目的
log.InfoLevel: writer,
log.WarnLevel: writer,
log.ErrorLevel: writer,
log.FatalLevel: writer,
log.PanicLevel: writer,
}, &log.JSONFormatter{})
log.AddHook(lfHook)
}
package Controller
import (
"src/Common/Unit"
"src/Config"
"time"
)
type ConfigChecker struct {
}
func (this *ConfigChecker) Start() {
this.startSysConfigChecker()
this.startSpsConfigChecker()
}
func (this *ConfigChecker) startSysConfigChecker() {
config := Config.GetInstance()
go func() {
START:
s, ok := config.Sys.Get("config_system_check_seconds")
if ok {
n := Unit.Time2Seconds(s.(string))
time.Sleep(time.Duration(n) * time.Second)
config.InitSysConfig()
}
goto START
}()
}
func (this *ConfigChecker) startSpsConfigChecker() {
config := Config.GetInstance()
go func() {
START:
s, ok := config.Sys.Get("config_sp_check_seconds")
if ok {
n := Unit.Time2Seconds(s.(string))
time.Sleep(time.Duration(n) * time.Second)
config.InitSpsConfig()
}
goto START
}()
}
package Controller
import (
cmap "github.com/orcaman/concurrent-map"
log "github.com/sirupsen/logrus"
"src/Common/DateTime"
"src/Common/Unit"
"src/Config"
"src/Model/Sp"
"strconv"
"time"
)
type SpChecker struct {
Config *Config.Config
queue cmap.ConcurrentMap
}
func (this *SpChecker) Start() {
this.queue =cmap.New()
//定时遍历SP,检查SP是否启动
go func() {
START:
s, ok := this.Config.Sys.Get("config_sp_check_seconds")
if ok {
this.check()
n := Unit.Time2Seconds(s.(string))+10
time.Sleep(time.Duration(n) * time.Second)
}
goto START
}()
}
func (this *SpChecker) check() {
for _, tmp := range this.Config.Sps.Items() {
sp := tmp.(map[string]interface{})
spid:= sp["id"].(string);
push_type,_:=strconv.Atoi(sp["push_type"].(string)) //0不推送,1推送
if push_type == 1 {
if !this.queue.Has(spid) {
this.queue.Set(spid, "running")
spModel := new(Sp.SpModel)
spModel.Config = this.Config
spModel.Spid = spid
st, _ := DateTime.Parse("YYYY-MM-DD hh:mm:ss", sp["push_offset"].(string))
spModel.StartTime = DateTime.Format("YYYYMMDDhhmmss", st)
go spModel.Start()
}
}else{
log.Infof("this sp do not need to push media , spinfo : %v",sp)
}
}
}
\ No newline at end of file
package Controller
import (
log "github.com/sirupsen/logrus"
"src/Common/Unit"
"src/Config"
"src/Model/Wasu"
"time"
)
type WasuChecker struct {
Config *Config.Config
}
func (this *WasuChecker) Start() {
go func() {
START:
s, ok := this.Config.Sys.Get("wasu_check_seconds")
if ok {
this.checkIncrementList()
n := Unit.Time2Seconds(s.(string))
time.Sleep(time.Duration(n) * time.Second)
}
goto START
}()
}
func (this *WasuChecker) checkIncrementList() {
log.Infoln("WasuChecker.checkIncrementList Starting...")
mediaModel := new(Wasu.MediaListModel)
mediaModel.Config = this.Config
//date := DateTime.Format("YYYYMMDD", time.Now())
date:="20171213"
mediaList := mediaModel.FetchList(date, 1)
ok := mediaModel.UpdateMediaList(mediaList)
if !ok {
log.Errorln("mediaModel.UpdateMediaList err: date=", date, "page=", 1)
}
if mediaList != nil {
pageNum := mediaList.PageNum
if pageNum >= 2 {
for page := 2; page <= pageNum; page++ {
mediaList := mediaModel.FetchList(date, page)
ok := mediaModel.UpdateMediaList(mediaList)
if !ok {
log.Errorln("mediaModel.UpdateMediaList err: date=", date, "page=", page)
}
}
}
}
}
package Sp
import (
"encoding/json"
"src/Common/Request"
"src/Config"
"unsafe"
)
type MediaListModel struct {
Config *Config.Config
}
type checkReqJson struct {
Spid string `json:"spid"`
Start string `json:"start"`
End string `json:"end"`
}
type checkRespJson struct {
Total int `json:"total"`
PageNum int `json:"page_num"`
}
type pushReqJson struct {
Spid string `json:"spid"`
Start string `json:"start"`
End string `json:"end"`
Page int `json:"page"`
PageNum int `json:"page_num"`
Url string `json:"url"`
Key string `json:"key"`
}
type pushRespJson struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
//检查
func (this *MediaListModel) check(reqJson *checkReqJson) (*checkRespJson,error) {
center_api_incrementCheck, ok := this.Config.Sys.Get("center_api_incrementCheck")
resp:=new(checkRespJson)
var err error
if ok {
jsonBody,_:=json.Marshal(reqJson)
data, err1 := Request.Post(center_api_incrementCheck.(string),*(*string)(unsafe.Pointer(&jsonBody)))
if err1 == nil {
err = json.Unmarshal([]byte(data), resp)
}else{
err=err1
}
}
return resp,err
}
//推送
func (this *MediaListModel) push(reqJson *pushReqJson) (*pushRespJson,error) {
center_api_incrementPush, ok := this.Config.Sys.Get("center_api_incrementPush")
resp:=new(pushRespJson)
var err error
if ok {
jsonBody,_:=json.Marshal(reqJson)
data, err1 := Request.Post(center_api_incrementPush.(string),*(*string)(unsafe.Pointer(&jsonBody)))
if err1 == nil {
err = json.Unmarshal([]byte(data), resp)
}else{
err=err1
}
}
return resp,err
}
//type Media struct {
// Id string `json:"id"`
// Title string `json:"title"`
// Description string `json:"description"`
// PlayUrl string `json:"playUrl"`
// PicUrl string `json:"picUrl"`
// Year string `json:"year"`
// Type string `json:"type"`
// Score string `json:"score"`
// Region string `json:"region"`
// Actor string `json:"actor"`
// Director string `json:"director"`
// HotelId string `json:"hotelId"`
// Status string `json:"status"`
// StatusInject string `json:"statusInject"`
//}
\ No newline at end of file
package Sp
import (
log "github.com/sirupsen/logrus"
"src/Common/DateTime"
"src/Common/Unit"
"src/Config"
"time"
)
type SpModel struct {
Config *Config.Config
Spid string
StartTime string
}
func (this *SpModel) Start() {
START:
log.Infoln("启动 SP检测:",this.Spid," offset:",this.StartTime)
config,ok := this.Config.Sps.Get(this.Spid)
n:=60
if ok {
conf,ok:=config.(map[string]interface{})
if ok {
push_check_seconds:=conf["push_check_seconds"].(string)
if push_check_seconds !="" {
n = Unit.Time2Seconds(push_check_seconds)
}
this.push();
}
}
time.Sleep(time.Duration(n) * time.Second)
goto START
}
func (this *SpModel) push() {
cReqJson:=new(checkReqJson)
cReqJson.Spid=this.Spid
cReqJson.Start = this.StartTime
cReqJson.End = DateTime.Format("YYYYMMDDhhmmss",time.Now())
mediaListModel:=new(MediaListModel)
mediaListModel.Config=this.Config
cRespJson,err:=mediaListModel.check(cReqJson)
if err==nil {
if cRespJson.PageNum>0 {
config,ok:=this.Config.Sps.Get(this.Spid)
if ok {
conf,ok:=config.(map[string]interface{})
if ok {
api_push:=conf["api_push"].(string)
api_key:=conf["api_key"].(string)
nOk:=0
for page := 1; page <= cRespJson.PageNum; page++ {
pReqJson := new(pushReqJson)
pReqJson.Start=cReqJson.Start
pReqJson.End = cReqJson.End
pReqJson.Spid=cReqJson.Spid
pReqJson.Page=page
pReqJson.PageNum=cRespJson.PageNum
pReqJson.Url=api_push
pReqJson.Key=api_key
pRespJson,err:=mediaListModel.push(pReqJson)
if err==nil {
if pRespJson.Code==0 {
nOk++
}else{
log.Errorf("PUSH MEDIA ERROR : reqJson:%v ,respJson:%v\n",pReqJson,pRespJson)
}
}else {
log.Errorf("PUSH MEDIA ERROR : reqJson:%v ,respJson:%v\n",pReqJson,pRespJson)
}
}
if nOk < cRespJson.PageNum{
log.Errorln("PUSH MEDIA ERROR : ok/total->",nOk,"/",cRespJson.PageNum)
}else {
log.Infoln("PUSH MEDIA SUCCESS : ",cReqJson," | ",cRespJson)
this.StartTime=cReqJson.End
}
}else{
log.Errorln("parse sp config err!")
}
}else {
log.Errorln("Get sp config err!")
}
}
}
}
\ No newline at end of file
package Wasu
import (
"encoding/json"
"fmt"
"github.com/sirupsen/logrus"
"src/Common/Request"
"src/Config"
"unsafe"
)
/**
{
"currentPage":1,
"pageNum":1,
"pageSize":2,
"total":2,
"list":[
{
"jsonUrl":"http://115.29.7.64:8092/XmlData/incrementJson?date=20190625&version=20190625150313",
"md5":"a3e0d11328e0feb3114921851f39ac41",
"newsId":"2018239",
"newsName":"冰雪女王",
"playUrl":"http://downloader.media.wasu.tv/data13/ott/344/2015-08/10/adc0650a31a5211ec6d0b1c9fdb10274/5d1496be/1439187357125_958916.ts"
}
]
}
**/
type Media struct {
JsonUrl string `json:"jsonUrl"`
//Md5 string `json:"md5"`
//NewsId string `json:"newsId"`
//NewsName string `json:"newsName"`
//PlayUrl string `json:"playUrl"`
}
type MediaList struct {
CurrentPage int `json:"currentPage"`
PageNum int `json:"pageNum"`
PageSize int `json:"pageSize"`
Total int `json:"total"`
List []*Media `json:"list"`
}
type MediaListModel struct {
Config *Config.Config
}
func (this *MediaListModel) FetchList(date string, page int) *MediaList {
wasu_api_incrementList, ok := this.Config.Sys.Get("wasu_api_incrementList")
mediaList := new(MediaList)
if ok {
url := fmt.Sprintf("%s?date=%s&page=%d", wasu_api_incrementList, date, page)
data, err := Request.Get(url)
if err == nil {
json.Unmarshal([]byte(data), mediaList)
}
}
return mediaList
}
func (this *MediaListModel) UpdateMediaList(mediaList *MediaList) bool {
l := len(mediaList.List)
nOk := 0
for _, media := range mediaList.List {
if this.UpdateMedia(media) {
nOk++
}
}
b := false
if nOk == l {
b = true
}
logrus.Debugln("UpdateMediaList : ok/total :", nOk, "/", l)
return b
}
func (this *MediaListModel) UpdateMedia(media *Media) bool {
center_api_media_update, ok := this.Config.Sys.Get("center_api_media_update")
b := false
if ok {
inData, _ := json.Marshal(media)
data, err := Request.Post(center_api_media_update.(string), *(*string)(unsafe.Pointer(&inData)))
if err == nil {
if data == "true" {
b = true
}
}
}
return b
}
[debug]
api_conf_sys = http://192.168.200.134:801/api/center/conf_sys #系统配置接口
api_conf_sps = http://192.168.200.134:801/api/center/conf_sps #合作方配置接口
log_path = ./
log_filename = center_service.log
[release]
module src
go 1.12
require (
github.com/araddon/dateparse v0.0.0-20190510211750-d2ba70357e92
github.com/bitly/go-simplejson v0.5.0
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirect
github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239 // indirect
github.com/imroc/req v0.2.4
github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869 // indirect
github.com/jonboulle/clockwork v0.1.0 // indirect
github.com/kr/pretty v0.1.0 // indirect
github.com/larspensjo/config v0.0.0-20160228172812-b6db95dc6321
github.com/lestrrat/go-envload v0.0.0-20180220120943-6ed08b54a570 // indirect
github.com/lestrrat/go-file-rotatelogs v0.0.0-20180223000712-d3151e2a480f
github.com/lestrrat/go-strftime v0.0.0-20180220042222-ba3bf9c1d042 // indirect
github.com/orcaman/concurrent-map v0.0.0-20190314100340-2693aad1ed75
github.com/pkg/errors v0.8.1
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5
github.com/sirupsen/logrus v1.4.2
github.com/stretchr/testify v1.3.0 // indirect
github.com/tebeka/strftime v0.0.0-20140926081919-3f9c7761e312 // indirect
golang.org/x/net v0.0.0-20190603091049-60506f45cf65 // indirect
)
github.com/araddon/dateparse v0.0.0-20190510211750-d2ba70357e92 h1:29yos9+rhKruIXuhBeY/jCvz0jZ/JndeIL/K6SFS90M=
github.com/araddon/dateparse v0.0.0-20190510211750-d2ba70357e92/go.mod h1:SLqhdZcd+dF3TEVL2RMoob5bBP5R1P1qkox+HtCBgGI=
github.com/bitly/go-simplejson v0.5.0 h1:6IH+V8/tVMab511d5bn4M7EwGXZf9Hj6i2xSwkNEM+Y=
github.com/bitly/go-simplejson v0.5.0/go.mod h1:cXHtHw4XUPsvGaxgjIAn8PhEWG9NfngEKAMDJEczWVA=
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY=
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239 h1:Ghm4eQYC0nEPnSJdVkTrXpu9KtoVCSo1hg7mtI7G9KU=
github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239/go.mod h1:Gdwt2ce0yfBxPvZrHkprdPPTTS3N5rwmLE8T22KBXlw=
github.com/imroc/req v0.2.4 h1:8XbvaQpERLAJV6as/cB186DtH5f0m5zAOtHEaTQ4ac0=
github.com/imroc/req v0.2.4/go.mod h1:J9FsaNHDTIVyW/b5r6/Df5qKEEEq2WzZKIgKSajd1AE=
github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869 h1:IPJ3dvxmJ4uczJe5YQdrYB16oTJlGSC/OyZDqUk9xX4=
github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869/go.mod h1:cJ6Cj7dQo+O6GJNiMx+Pa94qKj+TG8ONdKHgMNIyyag=
github.com/jonboulle/clockwork v0.1.0 h1:VKV+ZcuP6l3yW9doeqz6ziZGgcynBVQO+obU0+0hcPo=
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/larspensjo/config v0.0.0-20160228172812-b6db95dc6321 h1:HuvFF+bNfti7Q3taQTLox7YntC2IzUzM8pn2zyRTn98=
github.com/larspensjo/config v0.0.0-20160228172812-b6db95dc6321/go.mod h1:2tvhHYSOp38Gz/nhlXdCBepDFHG1/GCI0nuk4Dv9EyM=
github.com/lestrrat/go-envload v0.0.0-20180220120943-6ed08b54a570 h1:0iQektZGS248WXmGIYOwRXSQhD4qn3icjMpuxwO7qlo=
github.com/lestrrat/go-envload v0.0.0-20180220120943-6ed08b54a570/go.mod h1:BLt8L9ld7wVsvEWQbuLrUZnCMnUmLZ+CGDzKtclrTlE=
github.com/lestrrat/go-file-rotatelogs v0.0.0-20180223000712-d3151e2a480f h1:sgUSP4zdTUZYZgAGGtN5Lxk92rK+JUFOwf+FT99EEI4=
github.com/lestrrat/go-file-rotatelogs v0.0.0-20180223000712-d3151e2a480f/go.mod h1:UGmTpUd3rjbtfIpwAPrcfmGf/Z1HS95TATB+m57TPB8=
github.com/lestrrat/go-strftime v0.0.0-20180220042222-ba3bf9c1d042 h1:Bvq8AziQ5jFF4BHGAEDSqwPW1NJS3XshxbRCxtjFAZc=
github.com/lestrrat/go-strftime v0.0.0-20180220042222-ba3bf9c1d042/go.mod h1:TPpsiPUEh0zFL1Snz4crhMlBe60PYxRHr5oFF3rRYg0=
github.com/orcaman/concurrent-map v0.0.0-20190314100340-2693aad1ed75 h1:IV56VwUb9Ludyr7s53CMuEh4DdTnnQtEPLEgLyJ0kHI=
github.com/orcaman/concurrent-map v0.0.0-20190314100340-2693aad1ed75/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5 h1:mZHayPoR0lNmnHyvtYjDeq0zlVHn9K/ZXoy17ylucdo=
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5/go.mod h1:GEXHk5HgEKCvEIIrSpFI3ozzG5xOKA2DVlEX/gGnewM=
github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/tebeka/strftime v0.0.0-20140926081919-3f9c7761e312 h1:frNEkk4P8mq+47LAMvj9LvhDq01kFDUhpJZzzei8IuM=
github.com/tebeka/strftime v0.0.0-20140926081919-3f9c7761e312/go.mod h1:o6CrSUtupq/A5hylbvAsdydn0d5yokJExs8VVdx4wwI=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65 h1:+rhAzEzT3f4JtomfC371qB+0Ola2caSKcY69NUBZrRQ=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
package main
import (
log "github.com/sirupsen/logrus"
"runtime"
"src/Config"
. "src/Controller"
)
func main() {
log.SetLevel(log.DebugLevel)
config := Config.GetInstance()
err1 := config.InitSysConfig()
err2 := config.InitSpsConfig()
//初始化成功
if err1 == nil && err2 == nil {
configCHK := new(ConfigChecker)
configCHK.Start()
//华数媒资拉取
//wasuCHK := new (WasuChecker)
//wasuCHK.Config=config
//wasuCHK.Start()
//合作方媒资推送
spCHK :=new(SpChecker)
spCHK.Config=config
spCHK.Start()
} else {
log.Errorln("初始化系统配置错误:", err1)
log.Errorln("初始化合作方配置错误:", err2)
}
runtime.Goexit()
}
#! /bin/bash
#标准输出日志文件路径
LOG_PATH="./nohup.log"
#进程名
PROGRAM="SooonerIMTraffic"
BAK_TIME=""
while true ; do
sleep 10
PRO_NOW=`ps aux | grep $PROGRAM | grep -v grep | wc -l`
BAK_TIME=`date +%Y%m%d%H%M%S`
if [ $PRO_NOW -lt 1 ]; then
mv $LOG_PATH $LOG_PATH.bak$BAK_TIME
nohup ./$PROGRAM > $LOG_PATH 2>&1 &
date >> ./service_check.log
echo "start1" >> ./service_check.log
fi
done
exit 0
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment