Browse Source

完善api

renzheng 7 năm trước cách đây
mục cha
commit
42a3062af4

+ 41 - 1
README.md

@@ -1 +1,41 @@
-剑鱼企业服务
+剑鱼企业服务
+****
+
+1.access_token维护
+access_token为获取数据接口的凭据,access_token的有效期为2个小时,需定时刷新,重复获取上次获取的access_token将失效。
+
+请求方式: POST
+
+/api1/user/access_token?appid=jyMi1XQgMABQNcSkBMIhBq&key=6PzVlCUa
+参数说明:
+	参数			类型				说明			是否必须
+	appide		string	 	用户唯一标识	是
+	key			string	 	用户密码		是
+--------------
+返回数据
+响应头 :
+	content-encoding:gzip 
+	content-type:application/json 
+	accept-charset:utf-8
+响应内容:
+{
+    "access_token": string类型	
+    "code": 		int类型		返回代码
+    "times":		int类型		返回当天已调用次数,每天限制1000次
+}
+
+2.数据获取
+获取数据时需要携带access_token。
+
+请求方式: POST
+/api1/data/getdata?access_token=BHKSJyQ9z3bhI%2B7qB4BeGMmeFhSs3UNdKgOnxb%2Fp%2BjOQ%2BSKo
+参数说明:
+	参数			类型				说明						是否必须
+access_token	string			获取数据唯一凭据			是
+day				int				默认为0(-1取昨天)			否
+								(可取5天内数据范围[-5至0])
+next			int
+all				int
+
+
+

+ 1 - 1
jyservice/src/config.json

@@ -1,5 +1,5 @@
 {
- "webport":":88",
+ "webport":":8801",
  "mongodb": {
 		"addr":"192.168.3.207:27080",
 		"db":"jyqyfw",

+ 2 - 1
jyservice/src/main.go

@@ -10,10 +10,11 @@ import (
 
 func main() {
 	go Server()
+	//定时更新redis中的数据到数据库
 	log.Info("Start server...")
 	<-make(chan struct{}, 0)
 }
 
 func Server() {
-	http.ListenAndServe(utils.Sysconfig["webport"].(string), usermanager.Route)
+	http.ListenAndServe(utils.Sysconfig["webport"].(string), usermanager.Middleware(usermanager.Route))
 }

+ 28 - 14
jyservice/src/usermanager/access_token.go

@@ -3,15 +3,18 @@ package usermanager
 import (
 	"fmt"
 	"net/http"
+	"net/url"
 	"qfw/util/redis"
+	"sync"
 	"time"
 	. "utils"
+
 	//log "github.com/sirupsen/logrus"
 )
 
 const (
 	TOKEN_TIMEOUT     = 7200
-	TOKEN_LIMIT_TIMES = 201
+	TOKEN_LIMIT_TIMES = 1001
 	//key : 每天token上限tokenlimit_*  token的key token_*  每天调用数据api次数上限getlimit_*
 )
 
@@ -27,27 +30,38 @@ func GetAccessToken(w http.ResponseWriter, r *http.Request) {
 			"key":   key,
 		}, `{"_id":1}`)
 		if b && res != nil && *res != nil {
-			limitKey := fmt.Sprintf("tokenlimit_%s", appid)
+			GetDataMapLock.Lock()
+			appidLock := GetDataMap[appid]
+			if appidLock == nil {
+				appidLock = &sync.Mutex{}
+				GetDataMap[appid] = appidLock
+			}
+			GetDataMapLock.Unlock()
+			appidLock.Lock()
+			defer appidLock.Unlock()
+			t := time.Now()
+			limitKey := fmt.Sprintf("tokenlimit_%d_%s", t.Day(), appid)
 			limit := redis.GetInt(REDISDB, limitKey)
 			if limit < TOKEN_LIMIT_TIMES {
-				t := time.Now()
 				access_token := RsaEncrypt(fmt.Sprintf("%d,%s,%s", t.Unix(), appid, key))
 				if access_token != "" {
 					if redis.Put(REDISDB, "token_"+appid, access_token, TOKEN_TIMEOUT) {
-						d["code"] = CODE_SUCCESS
-						d["access_token"] = access_token
-						d["times"] = redis.Incr(REDISDB, limitKey)
-						tn := time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, time.Local).Unix()
-						expire := int(tn - t.Unix())
-						if expire > 0 {
-							redis.SetExpire(REDISDB, limitKey, expire)
+						d["access_token"] = url.QueryEscape(access_token)
+						if limit == 0 {
+							tn := time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, time.Local).Unix()
+							expire := int(tn - t.Unix())
+							limit++
+							redis.Put(REDISDB, limitKey, limit, expire)
+						} else {
+							redis.Incr(REDISDB, limitKey)
 						}
+						d["expires_in"] = TOKEN_TIMEOUT
 					}
 				}
 				if len(d) == 0 {
 					//服务出错
-					d["code"] = CODE_E2
-					d["msg"] = MSG_E2
+					d["code"] = CODE_ERR_E0
+					d["msg"] = MSG_ERR_E
 				}
 			} else {
 				//超过次数
@@ -57,8 +71,8 @@ func GetAccessToken(w http.ResponseWriter, r *http.Request) {
 		}
 	}
 	if len(d) == 0 {
-		d["code"] = CODE_E1
-		d["msg"] = MSG_E1
+		d["code"] = CODE_E2
+		d["msg"] = MSG_E2
 	}
 	WriteJSON(w, d)
 }

+ 184 - 148
jyservice/src/usermanager/getdata.go

@@ -4,10 +4,13 @@
 package usermanager
 
 import (
+	"fmt"
+	//	"encoding/json"
 	"net/http"
 	"qfw/util"
 	"qfw/util/redis"
 	"strings"
+	"sync"
 	"time"
 	. "utils"
 
@@ -21,178 +24,211 @@ const (
 	QUERY_LIMIT         = 100
 )
 
+var (
+	GetDataMap     = map[string]*sync.Mutex{}
+	GetDataMapLock = &sync.Mutex{}
+)
+
+//取增量数据
 func GetData(w http.ResponseWriter, r *http.Request) {
-	d := JSON{}
+	defer util.Catch()
 	access_token := r.FormValue("access_token")
-	log.Debug(access_token)
+	_, _, d := CheckUserInfo(access_token, 0, 0, 0)
+	WriteJSON(w, &d)
+}
+
+//取全量数据
+func GetAllData(w http.ResponseWriter, r *http.Request) {
+	defer util.Catch()
+	access_token := r.FormValue("access_token")
+	day := util.IntAll(r.FormValue("day"))
+	next := util.IntAll(r.FormValue("next"))
+	_, _, d := CheckUserInfo(access_token, day, next, 1)
+	WriteJSON(w, &d)
+}
+
+func CheckUserInfo(access_token string, day, next, all int) (bcheck bool, appid string, d JSON) {
+	d = JSON{}
+	//第一层判断token是否失效或格式不对
 	if access_token != "" {
 		at := RsaDecrypt(access_token)
-		b := false
+		log.Debug("token:", at)
 		if at != "" {
 			tn := time.Now().Unix()
 			arr := strings.Split(at, ",")
 			if len(arr) == 3 { //时间,appid,key
-				b = true
 				t := util.Int64All(arr[0])
 				des := tn - t
 				log.Debug("des", des)
-				if des >= 0 && des <= TOKEN_TIMEOUT {
-					appid := arr[1]
+				if des >= 0 && des <= TOKEN_TIMEOUT { //在有效时间内
+					appid = arr[1]
 					redis_token := redis.GetStr(REDISDB, "token_"+appid)
-					log.Debug("redis_token", redis_token, access_token)
-					if redis_token == access_token { //token验证通过,验证今日次数、总条数、服务时间
-						//"limittoday_" //值小于0时禁止
-						//"limitnum_" 值为小于零时实时判断
-						//"limittime_" 只判断一次,过期重新判断,用户续费时可以设置此值过期
-						limittime := redis.GetInt(REDISDB, "limittime_"+appid)
-						var THISNUM interface{}
-						if limittime < 1 {
-							res, bflag := Mgo.FindOneByField("user", &map[string]interface{}{
-								"appid": appid,
-							}, `{"plan":1}`)
-							if bflag && res != nil && *res != nil {
-								if m1 := util.ObjToMap((*res)["plan"]); m1 != nil {
-									THISNUM = (*m1)["current"]
-									starttime := util.Int64All((*m1)["starttime"])
-									endtime := util.Int64All((*m1)["endtime"])
-									if starttime <= tn && tn <= endtime { //在服务时间内
-										limittime = int(endtime - tn)
-										redis.Put(REDISDB, "limittime_"+appid, limittime, limittime) //存入值
-									}
-								}
-							}
-						}
-						if limittime > 0 { //在服务期内
-							//判断今日次数
-							limittoday := redis.Incr(REDISDB, "limittoday_"+appid)
-							if limittoday > GETDATA_LIMIT_TIMES { //当天调用超过次数
-
-							} else {
-								if limittoday == 1 { //设值过期时间
-									now := time.Now()
-									tomorrow := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, time.Local)
-									err := redis.SetExpire(REDISDB, "limittoday_"+appid, int(tomorrow.Unix()-now.Unix()))
-									if err != nil {
-										log.Error("set expire err!", err.Error())
-									}
-								}
-								limitnum := redis.Get(REDISDB, "limitnum_"+appid) //值
-								if limitnum == nil {                              //值为空时从数据库中提取
-									if THISNUM == nil {
-										res1, bflag1 := Mgo.FindOneByField("user", &map[string]interface{}{
-											"appid": appid,
-										}, `{"plan":1}`)
-										if bflag1 && res1 != nil && *res1 != nil {
-											if m1 := util.ObjToMap((*res1)["plan"]); m1 != nil {
-												THISNUM = (*m1)["current"]
-											}
-										}
-									}
-									if THISNUM != nil {
-										num := util.IntAll(THISNUM)
-										if num > 0 {
-											bparam := true
-											redis.Put(REDISDB, "limitnum_"+appid, num, 0)
-											//通过,可以返回取数据 day:0,all:1,next:0  ,100条
-											query := map[string]interface{}{"appid": appid}
-											i_all := util.IntAll(r.FormValue("all"))
-											if i_all == 1 {
-
-											} else if i_all != 0 {
-												bparam = false
-											} else {
-												query["bget"] = 0
-											}
-											i_day := util.IntAll(r.FormValue("all"))
-											createtime := map[string]interface{}{}
-											switch i_day { //保留最近5天数据
-											case 0:
-
-											case -1:
-											case -2:
-											case -3:
-											case -4:
-											default:
-												bparam = false
-											}
-											if i_day > -5 && i_day < 1 {
-												min, max := GetDayMinMax(time.Now().AddDate(0, 0, i_day))
-												createtime["$gte"] = min
-												createtime["$lte"] = max
-												query["createtime"] = createtime
-											} else {
-												bparam = false
-											}
-											if bparam {
-												log.Debug("query:", query)
-												i_next := util.IntAll(r.FormValue("next"))
-												data, bdata := Mgo.Find("usermail", query, `{"_id":1}`, `{"_id":0,"title":1,"detail":1,"publishtime":1,"href":1}`, false, i_next, QUERY_LIMIT)
-												if bdata && data != nil && *data != nil && len(*data) > 0 {
-													if i_all != 1 {
-														//更新
-														a1 := (*data)[0]
-														idq := map[string]interface{}{
-															"$gte": a1["_id"],
-														}
-														q1 := map[string]interface{}{
-															"appid": appid,
-														}
-														if len(*data) > 0 {
-															a2 := (*data)[len(*data)-1]
-															idq["$lte"] = a2["_id"]
-														}
-														q1["_id"] = idq
-														bupdate := Mgo.Update("usermail", q1, map[string]interface{}{
-															"$set": map[string]interface{}{
-																"bget": 1,
-															},
-														}, false, false)
-														if !bupdate {
-															log.Error("update get data error:", appid)
-														}
-													}
-													d["data"] = *data
-													if len(*data) == QUERY_LIMIT {
-														d["next"] = i_next + QUERY_LIMIT
-													} else {
-														d["next"] = -1
-													}
-												} else { //没有数据
-
-												}
-											}
-										}
-									}
-								}
-							}
-						}
+					log.Debug("redis_token", "\t", redis_token, "\t", access_token)
+					if redis_token != "" && redis_token == access_token { //token验证通过,验证今日次数、总条数、服务时间
+						bcheck = true
 					} else {
 						d["code"] = CODE_TOKEN_EXPIRE
 						d["msg"] = MSG_TOKEN_EXPIRE
 					}
-				} else { //超时
+				} else {
 					d["code"] = CODE_TOKEN_EXPIRE
 					d["msg"] = MSG_TOKEN_EXPIRE
 				}
 			}
 		}
-		if !b {
-			d["code"] = CODE_E0
-			d["msg"] = MSG_E0
-		}
-	} else {
+	}
+	if !bcheck && len(d) == 0 {
 		d["code"] = CODE_E1
 		d["msg"] = MSG_E1
 	}
-	WriteJSON(w, &d)
+	//第二层判断用户调用权限
+	if bcheck {
+		bcheck = false
+		tn := time.Now()
+		tnUnix := tn.Unix()
+		GetDataMapLock.Lock()
+		appidLock := GetDataMap[appid]
+		if appidLock == nil {
+			appidLock = &sync.Mutex{}
+			GetDataMap[appid] = appidLock
+		}
+		GetDataMapLock.Unlock()
+		appidLock.Lock()
+		defer appidLock.Unlock()
+		//"limittoday_" //值小于0时禁止
+		//"limitnum_" 值为小于零时实时判断
+		//"limittime_" 只判断一次,过期重新判断,用户续费时可以设置此值过期
+		validtime := redis.Get(REDISDB, "limittime_"+appid)
+		if validtime == nil {
+			if res, bflag := Mgo.FindOneByField("user", &map[string]interface{}{
+				"appid": appid,
+			}, `{"plan":1}`); bflag && res != nil && *res != nil && len(*res) > 0 {
+				if m1 := util.ObjToMap((*res)["plan"]); m1 != nil {
+					starttime := util.Int64All((*m1)["starttime"])
+					endtime := util.Int64All((*m1)["endtime"])
+					if starttime <= tnUnix && tnUnix <= endtime { //在服务时间内
+						limittime := int(endtime - tnUnix)
+						redis.Put(REDISDB, "limittime_"+appid, limittime, limittime) //存入值
+						validtime = limittime
+					}
+				}
+			}
+		}
+		limittodaykey := fmt.Sprintf("limittoday_%d_%s", tn.Day(), appid)
+		if validtime == nil {
+			d["code"] = CODE_ERR_E1
+			d["msg"] = MSG_ERR_E
+		} else {
+			limittime := util.IntAll(validtime)
+			if limittime > 0 { //在有效期内,判断今日调用次数,判断服务的总条数
+				limittoday := redis.GetInt(REDISDB, limittodaykey)
+				if limittoday > GETDATA_LIMIT_TIMES { //当天调用超过次数
+					d["code"] = CODE_E3
+					d["msg"] = MSG_E3
+				} else {
+					if limittoday == 0 {
+						_, max := GetDayMinMax(tn)
+						redis.Put(REDISDB, limittodaykey, 0, int(max-tnUnix))
+					}
+					//判断剩余服务条数
+					limitnum := redis.Get(REDISDB, "limitnum_"+appid) //值
+					if limitnum == nil {                              //值为空时从数据库中提取
+						if res1, bflag1 := Mgo.FindOneByField("user", &map[string]interface{}{
+							"appid": appid,
+						}, `{"plan":1}`); bflag1 && res1 != nil && *res1 != nil {
+							if m1 := util.ObjToMap((*res1)["plan"]); m1 != nil {
+								limitnum = (*m1)["current"]
+								if limitnum != nil {
+									redis.Put(REDISDB, "limitnum_"+appid, limitnum, 0)
+								}
+							}
+						}
+					}
+					if limitnum == nil {
+						d["code"] = CODE_ERR_E3
+						d["msg"] = MSG_ERR_E
+					} else {
+						num := util.IntAll(limitnum)
+						if num < 1 {
+							d["code"] = CODE_E5
+							d["msg"] = MSG_E5
+						} else {
+							bcheck = true
+						}
+					}
+				}
+			} else {
+				d["code"] = CODE_E4
+				d["msg"] = MSG_E4
+			}
+		}
+		//判断通过
+		if bcheck { //取数据
+			next, infos := getDataByAppid(appid, day, next, all, limittodaykey)
+			if all == 1 && next > 0 {
+				d["next"] = next
+			}
+			if len(infos) == 0 {
+				d["data"] = []map[string]interface{}{}
+			} else {
+				d["data"] = infos
+			}
+		}
+	}
+	return
 }
 
-//sess := Mgo.GetMgoConn()
-//defer Mgo.DestoryMongoConn(sess)
-//it := sess.DB(Mgo.DbName).C("usermail").Find(&query).Sort("-publishtime").Select(map[string]interface{}{
-//	"_id": 0, "title": 1, "detail": 1, "publishtime": 1, "href": 1,
-//}).Skip(i_next).Limit(100).Iter()
-//n := 0
-//for tmp := make(map[string]interface{}); it.Next(&tmp); n++ {
+//获取数据
+func getDataByAppid(appid string, i_day, next, i_all int, limittodaykey string) (i_next int, infos []map[string]interface{}) {
+	query := map[string]interface{}{"appid": appid}
+	blastid := false
+	if i_all == 0 { //必须是当天才能使用lastid按顺序取信息
+		blastid = true
+		lastid := redis.GetStr(REDISDB, "lastid_"+appid)
+		if lastid != "" {
+			query["_id"] = map[string]interface{}{
+				"$gt": util.StringTOBsonId(lastid),
+			}
+		}
+	}
+	createtime := map[string]interface{}{}
+	if !blastid && i_day > -6 && i_day < 1 {
+		min, max := GetDayMinMax(time.Now().AddDate(0, 0, i_day))
+		createtime["$gte"] = min
+		createtime["$lte"] = max
+		query["createtime"] = createtime
+	}
 
-//}
+	log.Debug("query:", query)
+	i_next = next
+	data, bdata := Mgo.Find("usermail", query, `{"_id":1}`, `{"title":1,"detail":1,"publishtime":1,"href":1}`, false, i_next, QUERY_LIMIT)
+	if bdata && data != nil && *data != nil && len(*data) > 0 {
+		infos = *data
+		if blastid {
+			lastid := util.BsonIdToSId((*data)[len(*data)-1]["_id"])
+			if lastid != "" {
+				redis.Put(REDISDB, "lastid_"+appid, lastid, DesZero())
+			}
+		}
+		for _, v := range infos {
+			delete(v, "_id")
+		}
+		if len(*data) == QUERY_LIMIT && !blastid {
+			i_next = i_next + QUERY_LIMIT
+		} else {
+			i_next = -1
+		}
+		//处理总条数
+		redis.Decrby(REDISDB, "limitnum_"+appid, len(*data))
+		go Mgo.Save("userdatalog", map[string]interface{}{
+			"appid":   appid,
+			"datalen": len(*data),
+			"date":    time.Now().Unix(),
+		})
+	} else { //没有数据
+		i_next = 0
+	}
+	//处理今日调用次数
+	redis.Incr(REDISDB, limittodaykey)
+	return
+}

+ 41 - 0
jyservice/src/usermanager/task.go

@@ -0,0 +1,41 @@
+package usermanager
+
+import (
+	"qfw/util"
+	"qfw/util/redis"
+	"time"
+	. "utils"
+
+	log "github.com/sirupsen/logrus"
+)
+
+func init() {
+	//定时修改redis中的数据总条数到数据库
+	go func() {
+		for {
+			tn := time.Now()
+			_, max := GetDayMinMax(tn)
+			des := max - tn.Unix()
+			log.Debug("启动定时任务:", des)
+			time.Sleep(time.Duration(des) * time.Second)
+			//更新数据
+			keys := redis.GetKeysByPattern(REDISDB, "limitnum_*")
+			for _, key := range keys {
+				k := string(key.([]uint8))
+				v := redis.Get(REDISDB, k)
+				if v != nil {
+					val := util.IntAll(v)
+					b := Mgo.Update("user", `{"appid":"`+k[9:]+`"}`, map[string]interface{}{
+						"$set": map[string]interface{}{
+							"plan.current": val,
+						},
+					}, false, false)
+					log.Debug("更新剩余条数到数据库:", b, " val:", val, " appid: ", k[9:])
+				}
+			}
+			//清空
+			//redis.DelByCodePattern(REDISDB, "tokenlimit_*")
+			//redis.DelByCodePattern(REDISDB, "limittoday_*")
+		}
+	}()
+}

+ 116 - 5
jyservice/src/usermanager/usermanager.go

@@ -1,9 +1,15 @@
 package usermanager
 
 import (
+	"net"
 	"net/http"
+	"strings"
+	"sync"
+	"time"
+	. "utils"
 
 	"github.com/gorilla/mux"
+	log "github.com/sirupsen/logrus"
 )
 
 var (
@@ -11,9 +17,114 @@ var (
 )
 
 func init() {
-	Route.HandleFunc("/api1/user/access_token", GetAccessToken).Methods("POST")
-	Route.HandleFunc("/api1/user/newuser", NewUser).Methods("POST")
-	Route.HandleFunc("/api1/user/newservice", NewService).Methods("POST")
-	Route.HandleFunc("/api1/data/getdata", GetData).Methods("POST")
-	http.Handle("/", Route)
+	//用户使用地址
+	Route.HandleFunc("/user/access_token", GetAccessToken).Methods("POST")
+	Route.HandleFunc("/data/getdata", GetData).Methods("POST")
+	Route.HandleFunc("/data/getalldata", GetAllData).Methods("POST")
+	//管理地址
+	Route.HandleFunc("/api1/user/jy_newuser", NewUser).Methods("POST")
+	Route.HandleFunc("/api1/user/jy_newservice", NewService).Methods("POST")
+
+	//http.Handle("/", middleware(Route))
+	go SaveLogTask()
+}
+
+func Middleware(next http.Handler) http.Handler {
+	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+		//访问时间控制去掉
+		//fmt.Println("before")
+		//		t := time.Now()
+		//		if t.Hour() > 22 || t.Hour() < 6 {
+		//			WriteJSON(w, &JSON{
+		//				"code": CODE_OUTTIME,
+		//				"msg":  MSG_OUTTIME,
+		//			})
+		//			return
+		//		}
+		//记录日志
+		go addLog(req)
+		next.ServeHTTP(w, req)
+		//fmt.Println("after")
+	})
+}
+
+//定时保存日志
+func SaveLogTask() {
+	lock.Lock()
+	if len(arr) >= 1 {
+		tmp := arr
+		arr = make([]map[string]interface{}, 0)
+		go func() {
+			log.Debug("timer..save..visit..log", len(tmp))
+			Mgo.SaveBulk("logs", tmp...)
+		}()
+	}
+	lock.Unlock()
+	time.AfterFunc(2*time.Minute, SaveLogTask)
+}
+
+//内存缓存日志数量,超过此数量存库
+var nc = 50
+
+//内存缓存日志map
+var arr = make([]map[string]interface{}, 0)
+
+//对map的同步
+var lock sync.Mutex
+
+//用线程处理,增加日志
+
+func addLog(req *http.Request) {
+	timeNow := time.Now()
+	agent := req.Header.Get("user-agent")
+	ref := req.Referer()
+	s_url := req.RequestURI
+	date := timeNow.Unix()
+	logs := map[string]interface{}{
+		"l_date":     date,
+		"s_ip":       req.Proto,
+		"s_refer":    ref,
+		"i_year":     timeNow.Year(),
+		"i_month":    timeNow.Month(),
+		"i_day":      timeNow.Day(),
+		"i_hour":     timeNow.Hour(),
+		"i_minutes":  timeNow.Minute(),
+		"s_describe": req.Form,
+		"s_client":   agent,
+		"s_method":   req.Method,
+		"s_url":      s_url,
+	}
+	lock.Lock()
+	arr = append(arr, logs)
+	if len(arr) >= nc || s_url == "/sl" {
+		tmp := arr
+		arr = make([]map[string]interface{}, 0)
+		go func() {
+			log.Println("save..visit..log", len(tmp))
+			Mgo.SaveBulk("logs", tmp...)
+		}()
+	}
+	lock.Unlock()
+}
+
+//获取请求ip
+func GetIp(req *http.Request) string {
+	if req == nil {
+		return ""
+	}
+	ip_for := req.Header.Get("x-forwarded-for")
+	ip_client := req.Header.Get("http_client_ip")
+	ip_addr := req.Header.Get("Remote_addr")
+	un := "unknown"
+	if (ip_for != un) && (len(strings.TrimSpace(ip_for)) > 0) {
+		return ip_for
+	}
+	if (ip_client != un) && (len(strings.TrimSpace(ip_client)) > 0) {
+		return ip_client
+	}
+	if (ip_addr != un) && (len(strings.TrimSpace(ip_addr)) > 0) {
+		return ip_addr
+	}
+	ip, _, _ := net.SplitHostPort(req.RemoteAddr)
+	return ip
 }

+ 38 - 0
jyservice/src/utils/gzip.go

@@ -0,0 +1,38 @@
+package utils
+
+import (
+	"bytes"
+	"compress/gzip"
+	"io/ioutil"
+)
+
+func GzipEncode(in []byte) ([]byte, error) {
+	var (
+		buffer bytes.Buffer
+		out    []byte
+		err    error
+	)
+	writer := gzip.NewWriter(&buffer)
+	_, err = writer.Write(in)
+	if err != nil {
+		writer.Close()
+		return out, err
+	}
+	err = writer.Close()
+	if err != nil {
+		return out, err
+	}
+
+	return buffer.Bytes(), nil
+}
+
+func GzipDecode(in []byte) ([]byte, error) {
+	reader, err := gzip.NewReader(bytes.NewReader(in))
+	if err != nil {
+		var out []byte
+		return out, err
+	}
+	defer reader.Close()
+
+	return ioutil.ReadAll(reader)
+}

+ 14 - 4
jyservice/src/utils/httputil.go

@@ -1,18 +1,28 @@
 package utils
 
 import (
+	"compress/gzip"
 	"encoding/json"
 	"net/http"
 
 	log "github.com/sirupsen/logrus"
 )
 
+//开启gzip压缩
 func WriteJSON(w http.ResponseWriter, data interface{}) {
-	resByte, err := json.Marshal(data)
+	//	resByte, err := json.Marshal(data)
+	//	if err != nil {
+	//		log.Error("writejson err", err.Error())
+	//		return
+	//	}
+	w.Header().Set("Accept-Charset", "utf-8")
+	w.Header().Set("Content-Type", "application/json")
+	w.Header().Set("Content-Encoding", "gzip")
+	gz := gzip.NewWriter(w)
+	defer gz.Close()
+	err := json.NewEncoder(gz).Encode(data)
 	if err != nil {
 		log.Error("writejson err", err.Error())
-		return
 	}
-	w.Header().Set("Content-Type", "application/json")
-	w.Write(resByte)
+	//w.Write(resByte)
 }

+ 25 - 9
jyservice/src/utils/utils.go

@@ -12,17 +12,27 @@ import (
 type JSON map[string]interface{}
 
 const (
-	REDISDB           = "jyqyfw"
-	CODE_TOKEN_EXPIRE = 1001 //token过期
+	REDISDB = "jyqyfw"
+	//	CODE_OUTTIME      = 0
+	//	MSG_OUTTIME       = "不在服务时间(服务时间06:00-23:00)"
+	CODE_TOKEN_EXPIRE = 1000 //token过期
 	MSG_TOKEN_EXPIRE  = "token已过期"
-	CODE_E0           = 10011
-	MSG_E0            = "token错误"
-	CODE_E1           = 1002
-	MSG_E1            = "参数错误"
-	CODE_E2           = 1003
-	MSG_E2            = "服务出错"
-	CODE_E3           = 1004
+	CODE_E1           = 1001
+	MSG_E1            = "token错误"
+	CODE_E2           = 1002
+	MSG_E2            = "参数错误"
+	CODE_E3           = 1003
 	MSG_E3            = "调用次数过超限制"
+	CODE_E4           = 1004
+	MSG_E4            = "服务过期"
+	CODE_E5           = 1005
+	MSG_E5            = "服务条数过超限制"
+	CODE_ERR_E0       = 4000
+	MSG_ERR_E         = "内部错误"
+	CODE_ERR_E1       = 4001
+	CODE_ERR_E2       = 4002
+	CODE_ERR_E3       = 4003
+	CODE_ERR_E4       = 4004
 	//------
 	CODE_SUCCESS = 1
 	MSG_SUCCESS  = "请求成功"
@@ -54,3 +64,9 @@ func GetDayMinMax(t time.Time) (int64, int64) {
 	min := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local).Unix()
 	return min, min + 86400
 }
+
+func DesZero() int {
+	t := time.Now()
+	d := time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, time.Local).Unix()
+	return int(d - t.Unix())
+}