Prechádzať zdrojové kódy

Merge branch 'develop' of 192.168.3.17:zhanghongbo/qfw into develop

renzheng 9 rokov pred
rodič
commit
ddcac18a2c

+ 1 - 1
common/src/qfw/util/encrypt_test.go

@@ -67,6 +67,6 @@ func Test_int(t *testing.T) {
 
 func TestActivity(t *testing.T) {
 	se := SimpleEncrypt{Key: "topnet2015topnet2015"}
-	tmp := se.EncodeString("oZQC_s7VTU3p9SrhU27gA5v2MDk0")
+	tmp := se.EncodeString("obEpLuPmkfICwGUh8U3nwN_UK3qY")
 	log.Println(tmp, se.DecodeString(tmp))
 }

+ 13 - 16
core/src/qfw/active/activemanage.go

@@ -64,7 +64,6 @@ func (a *Activemanage) Luckdraw(activecode, id string) error {
 		if *u != nil {
 			if ret := redis.Get("other", "cj_"+openid+"_"+time.Now().Format("2006_01_02")); ret == nil {
 				//a.T = *u
-				fmt.Println("ret:::::::::", ret, "33333333333", time.Now().Format("2006_01_02"))
 				a.T["flog"] = "A"
 				Tm := time.Now().AddDate(0, 0, 1)
 				if ret := redis.Get("other", "cj_"+openid+"_"+Tm.Format("2006_01_02")); ret == nil {
@@ -102,7 +101,6 @@ func (a *Activemanage) Getluckdraw() error {
 		if *u != nil {
 			if ret := redis.Get("other", "cj_"+openid+"_"+time.Now().Format("2006_01_02")); ret == nil {
 				//a.T = *u
-				fmt.Println("ret22:::::::::", ret)
 				a.T["flog"] = "A"
 				a.T["msg"] = "小主莫贪心,每天只有一次抽奖机会呦!分享至朋友圈或好友即可以获得明天抽奖资格呦!乖,快去分享吧!大奖可能就在明天~~"
 				return a.Write(`{"flog":"` + flog + `","msg":"` + msg + `"}`)
@@ -161,24 +159,23 @@ func (a *Activemanage) Getluckdraw() error {
 		}
 		msg = "  小主是真真的好运气," + s_prize + "落入您囊中。红包将由系统自动发放到您的微信,请注意查收。<br/><br/>分享至朋友圈或好友即可以获得明天抽奖资格呦!乖,快去分享吧!大奖可能就在明天~~"
 	} else if (i > 275 && i < 310) || (i > 95 && i < 130) {
-		id := a.GetSession("userid").(string)
-		b := credit.UpuserCreditSession(id, "b6", "B", nil, a.Action)
+		//时间判断,提醒不同
+		//now := time.Now()
+		//不在工作时间
+		//if now.Weekday() == 6 || now.Weekday() == 0 || (now.Hour() > 18 || now.Hour() < 9) {
+		//
+		//	msg = "  小主是真真的好运气," + s_prize + "落入您囊中!<br/>  请在微信留下您的联系方式(手机号或qq号),企明星客服会在下一个工作日9:00-17:00给小主回复哦!<br/>  小主翻个牌子,动动小手分享活动,么么哒……(分享点击页面右上方···分享到朋友圈)"
+		//} else { //在工作时间
+		msg = "  小主是真真的好运气," + s_prize + "落入您囊中。请将您的联系方式和邮寄地址留言给企明星。我们会在活动截止后尽快为您发出。<br/><br/>分享至朋友圈或好友即可以获得明天抽奖资格呦!乖,快去分享吧!大奖可能就在明天~~"
+		//}
+	} else if i > 140 && i < 175 {
+		obid := BsonIdToSId(a.GetSession("userid"))
+		b := credit.UpuserCreditSession(obid, "b6", "B", nil, a.Action)
 		if b == true {
-			//时间判断,提醒不同
-			//now := time.Now()
-			//不在工作时间
-			//if now.Weekday() == 6 || now.Weekday() == 0 || (now.Hour() > 18 || now.Hour() < 9) {
-			//
-			//	msg = "  小主是真真的好运气," + s_prize + "落入您囊中!<br/>  请在微信留下您的联系方式(手机号或qq号),企明星客服会在下一个工作日9:00-17:00给小主回复哦!<br/>  小主翻个牌子,动动小手分享活动,么么哒……(分享点击页面右上方···分享到朋友圈)"
-			//} else { //在工作时间
-			msg = "  小主是真真的好运气," + s_prize + "落入您囊中。请将您的联系方式和邮寄地址留言给企明星。我们会在活动截止后尽快为您发出。<br/><br/>分享至朋友圈或好友即可以获得明天抽奖资格呦!乖,快去分享吧!大奖可能就在明天~~"
-			//}
+			msg = "  小主是真真的好运气,200积分落入您囊中。积分将由系统自动发放到您的企明星账户,请登录www.qmx.top查看。<br/><br/>分享至朋友圈或好友即可以获得明天抽奖资格呦!乖,快去分享吧!大奖可能就在明天~~"
 		} else {
 			msg = "  抽奖出错!小主不要桑心,联系企明星管理员,200积分还是您的!"
 		}
-
-	} else if i > 140 && i < 175 {
-		msg = "  小主是真真的好运气,200积分落入您囊中。积分将由系统自动发放到您的企明星账户,请登录www.qmx.top查看。<br/><br/>分享至朋友圈或好友即可以获得明天抽奖资格呦!乖,快去分享吧!大奖可能就在明天~~"
 	} else { //不中奖
 		msg = "  小主不要桑心,这次没有中奖哦,明天记得要来拼运气啊!<br/><br/>分享至朋友圈或好友即可以获得明天抽奖资格呦!乖,快去分享吧!大奖可能就在明天~~"
 	}

+ 1 - 1
core/src/timetask.json

@@ -1 +1 @@
-{"comment":{"c_rate":720,"commentrate":900},"market":{"demand":{"attr":["i_hits","i_bids","i_status"],"timepoint":"2016-01-26 08:13:30"},"service":{"attr":["i_hits","i_sales","i_comments","i_score","i_appcounts"],"timepoint":"2016-01-26 08:13:30"}},"marketisstart":true,"marketrate":300}
+{"comment":{"c_rate":720,"commentrate":900},"market":{"demand":{"attr":["i_hits","i_bids","i_status"],"timepoint":"2016-01-26 10:41:42"},"service":{"attr":["i_hits","i_sales","i_comments","i_score","i_appcounts"],"timepoint":"2016-01-26 10:41:42"}},"marketisstart":true,"marketrate":300}

+ 1 - 0
core/src/web/staticres/css/dev-qfw.css

@@ -33,6 +33,7 @@ a{
 }
 .font-size-12{
 	font-size: 12px;
+	font-family: tahoma, arial, 'Hiragino Sans GB', 宋体, sans-serif;
 }
 .font-size-10{
 	font-size: 10px;

+ 9 - 4
core/src/web/staticres/css/entcommunity.css

@@ -145,13 +145,13 @@ a:focus, a:hover{
 	color: #A0A0A0;
 }
 .entinfo-page .b-com-head .b-com-last .glyphicon{
-	font-size: 18px;
+	font-size: 17px;
 	color: #cccccc;
 	margin-right: 5px;
 	vertical-align: sub;
 }
 .entinfo-page .b-com-head .b-com-last a{
-	color: blue;
+	color: #415fcf;
 }
 .white_content {
 	display: none;
@@ -194,6 +194,7 @@ a:focus, a:hover{
 	height: 50px;
 	background-color: #F6F8FA;
 	padding-left: 20px;
+	font-size: 16px;
 }
 .ent-tab li{
 	padding: 0px 20px;
@@ -285,10 +286,11 @@ a:focus, a:hover{
 	color: #16a086;
 	display: inline-block;
 	margin-bottom: 5px;
+	font-weight: bold;
 }
 .entinfo-basicinfo .entinfo-round>div>div>span.entinfo-disabled{
-	background-color: #f0f0f0;
-	color: #a0a0a0;
+	background-color: #dddddd;
+	color: #7f7f7f;
 }
 .entinfo-basicinfo .entinfo-round>div>div>span:nth-child(2){
 	text-overflow: ellipsis;
@@ -625,6 +627,9 @@ a:focus, a:hover{
 	font-size: 14px;
 	margin-left: 5px;
 }
+.ent-layout-up .b-com-title font a{
+	color: #415fcf;
+}
 .ent-layout-up .b-com-content{
 	padding-top: 30px;
 }

BIN
core/src/web/staticres/images/activeimages/lotteryBg.jpg


+ 6 - 4
core/src/web/staticres/wxswordfish/main.js

@@ -252,9 +252,11 @@ function showSnopshot(module,type,on){
 		try{
 			var days=eval("msgset."+module+".days")	
 			if(typeof days=="number"){
-				var tiptxt="本栏目推送服务期还剩<d style='color:red'>"+days+"</d>天"
-				if(winWidth<341){
-					tiptxt="服务期还剩<d style='color:red'>"+days+"</d>天"
+				if (days<6){
+					var tiptxt="本栏目推送服务期还剩<d style='color:red'>"+days+"</d>天"
+					if(winWidth<341){
+						tiptxt="服务期还剩<d style='color:red'>"+days+"</d>天"
+					}
 				}
 			}
 		}catch(e){}
@@ -520,6 +522,6 @@ $(function(){
 
 	//剑鱼协议
 	if(winWidth<341){
-		$("#prexieyi").html("");
+		$("#prexieyi").append("<br>");
 	}
 });

+ 3 - 0
core/src/web/staticres/wxswordfish/share.js

@@ -1,4 +1,7 @@
 function initShare(signature,shareid){
+	if(typeof(shareid) == "undefined" || shareid == null || shareid == ""){
+		shareid = "-1";
+	}
 	if(typeof(signature) != "undefined" && signature != null && signature.length == 4){
 		wx.config({
 		    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。

+ 3 - 3
core/src/web/templates/swordfish/protocoltxt.html

@@ -18,7 +18,7 @@
 	<p class="pinden">2,从原始信息发布到您收到剑鱼推送信息会经过一个复杂的技术处理和网络传输过程,企明星对您收到剑鱼推送信息的时间延迟指标不做承诺。由于您未能在某个时间内收到剑鱼推送信息而造成的任何结果,企明星不承担责任。</p>
 	<p class="pinden">3,企明星保证您收到的剑鱼推送信息符合您指定的订阅条件。企明星不保证您收到的剑鱼推送信息准确符合您的真实意图。</p>
 	<p class="pinden">4,您保证您使用剑鱼的设备以及微信App正常运行。如果由于您使用剑鱼的设备或微信App的问题造成您无法接收剑鱼推送信息,企明星不承担责任。</p>
-	<div class="col-xs-12 hidden-sm hidden-md hidden-lg" style="text-align:center;">
-	 <button class="btn btn-primary" onclick="window.location.href='/swordfish/page'" style="padding-top:3px;padding-bottom:3px;">返回</button></td>
-	</div>
+</div>
+<div class="col-xs-12 hidden-sm hidden-md hidden-lg" style="text-align:center;padding:0 0 50px 50px">
+	<button class="btn btn-primary" onclick="window.location.href='/swordfish/page'" style="padding-top:3px;padding-bottom:3px;">返回</button>
 </div>

+ 6 - 2
core/src/web/templates/swordfish/rssset.html

@@ -36,7 +36,9 @@
 				{{if .T.msgset}}
 					{{if .T.msgset.tender}}
 						{{if .T.msgset.tender.day}}
-						本栏目推送服务期还剩{{.T.msgset.tender.day}}天。想要服务不间断,请确保积分充足。 <a href="/member/credit/myCredit">去做任务赚积分</a>
+							{{if gt 6 .T.msgset.tender.day}}
+							本栏目推送服务期还剩{{.T.msgset.tender.day}}天。想要服务不间断,请确保积分充足。 <a href="/member/credit/myCredit">去做任务赚积分</a>
+							{{end}}
 						{{end}}
 					{{end}}
 				{{end}}
@@ -70,7 +72,9 @@
 				{{if .T.msgset}}
 					{{if .T.msgset.bid}}
 						{{if .T.msgset.bid.day}}
-						本栏目推送服务期还剩{{.T.msgset.bid.day}}天。想要服务不间断,请确保积分充足。 <a href="/member/credit/myCredit">去做任务赚积分</a>
+							{{if gt 6 .T.msgset.bid.day}}
+							本栏目推送服务期还剩{{.T.msgset.bid.day}}天。想要服务不间断,请确保积分充足。 <a href="/member/credit/myCredit">去做任务赚积分</a>
+							{{end}}
 						{{end}}
 					{{end}}
 				{{end}}

+ 0 - 3
core/src/web/templates/swordfish/wxindex.html

@@ -8,9 +8,6 @@
 <script src="/js/jquery.js"></script>
 <script src="/wxswordfish/share.js"></script>
 <script src="/swiper/swiper.min.js"></script>
-<script>
-	var shareid="{{.T.shareid}}";
-</script>
 </head>
 <body>
 <div class="swiper-container">

+ 0 - 1
core/src/web/templates/swordfish/wxpush.html

@@ -7,7 +7,6 @@
 <script src="/js/jquery.js"></script>
 <script src="/wxswordfish/share.js"></script>
 <script>
-	var shareid="{{.T.shareid}}";
 $(function(){
 	var hm = document.createElement("script");
 	hm.src = "//hm.baidu.com/hm.js?ed198b177e527bb53684db20bb390e77";

+ 0 - 1
core/src/web/templates/swordfish/wxrssset.html

@@ -11,7 +11,6 @@
 <script src="/wxswordfish/main.js"></script>
 <script>
 	var msgset= {{.T.msgset}};
-	var shareid="{{.T.shareid}}";
 </script>
 </head>
 <body>

+ 1 - 1
core/src/web/templates/swordfish/wxtoolbar.html

@@ -107,7 +107,7 @@ $(function(){
 		}
 	});
 	//
-	initShare({{.T.signature}},typeof(shareid)=="undefined"?"-1":shareid);
+	initShare({{.T.signature}},{{.T.shareid}});
 });
 //意见反馈
 function Feedback(){

+ 20 - 5
core/src/web/templates/yellowpage/enterpriseinfo.html

@@ -88,7 +88,7 @@
 					</span>
 					<input id="location" type="hidden" value="{{if .T.res.Dom}}{{.T.res.Dom}}{{end}}">
 					<input id="cityname" type="hidden" value="">
-					<a href="javascript:void(0)" onclick="showMap()">查看详细地图</a>
+					<a href="javascript:void(0)" class="font-size-12" onclick="showMap()">查看详细地图</a>
 				{{end}}
 			</div>
 		</div>
@@ -124,7 +124,7 @@
 			<div class="entinfo-basicinfo ent-layout-up">
 				<div class="b-com-title">
 					<span class="glyphicon jianzhu"></span>基本信息
-					<font>(来源:<a href="http://gsxt.saic.gov.cn/" rel="nofollow" style="text-decoration: underline;color: #0099FF;">全国企业信用信息公示系统</a>)</font>
+					<font>(来源:<a href="http://gsxt.saic.gov.cn/" rel="nofollow">全国企业信用信息公示系统</a>)</font>
 				</div>
 				<div class="b-com-content">
 					<div class="entinfo-round">
@@ -143,7 +143,23 @@
 									</span>
 									<br>
 									{{end}}
-									{{if .T.res.EntName}}{{.T.res.EntName}}{{end}}
+									{{if .T.res.EntName}}
+									<script>
+										var entName = {{.T.res.EntName}};
+										if(entName.length > 15){
+											var firstLine = entName.substring(0,15);
+											var secondLine = entName.substring(15,entName.length);
+											console.info(secondLine);
+											if(secondLine.length > 15){
+												secondLine = secondLine.substring(0,12)+"...";
+											}
+											document.write(firstLine+"<br>"+secondLine);
+										}else{
+											document.write(entName);
+										}
+										
+									</script>
+									{{end}}
 								</div>
 								<br><img src="/images/entcommunity/triangle.png">
 							</span>
@@ -181,7 +197,7 @@
 						<!--公司类型-->
 					  	<div class="entinfo-enttype">
 							<div>
-								<span{{if not .T.res.EntTypeName}} class="entinfo-disabled"{{end}}>公司类型</span>
+								<span{{if not .T.res.EntTypeName}} class="entinfo-disabled"{{end}}>企业类型</span>
 								<span>{{if .T.res.EntTypeName}}{{.T.res.EntTypeName}}{{end}}</span>
 							</div>
 							<img src="/images/entcommunity/gongsileixing.png">
@@ -258,7 +274,6 @@
 					<span class="clearfix"></span>
 				</div>
 			</div>
-			{{end}}
 			{{if and (not .T.res.gs) (not .T.res.investor)}}
 			<div class="ent-findnull">
 				<img src="/images/findnull.png" class="b-findnull">

+ 6 - 0
weixin/src/endless/doc.go

@@ -0,0 +1,6 @@
+/*
+endless provides a drop in  replacement for the `net/http` stl functions `ListenAndServe` and `ListenAndServeTLS` to achieve zero downtime restarts and code upgrades.
+
+The code is based on the excellent post [Graceful Restart in Golang](http://grisha.org/blog/2014/06/03/graceful-restart-in-golang/) by [Grisha Trubetskoy](https://github.com/grisha). I took his code as a start. So a lot of credit to Grisha!
+*/
+package endless

+ 560 - 0
weixin/src/endless/endless.go

@@ -0,0 +1,560 @@
+package endless
+
+import (
+	"crypto/tls"
+	"errors"
+	"flag"
+	"fmt"
+	"log"
+	"net"
+	"net/http"
+	"os"
+	"os/exec"
+	"os/signal"
+	"runtime"
+	"strings"
+	"sync"
+	"syscall"
+	"time"
+
+	// "github.com/fvbock/uds-go/introspect"
+)
+
+const (
+	PRE_SIGNAL = iota
+	POST_SIGNAL
+
+	STATE_INIT
+	STATE_RUNNING
+	STATE_SHUTTING_DOWN
+	STATE_TERMINATE
+)
+
+var (
+	runningServerReg     sync.RWMutex
+	runningServers       map[string]*endlessServer
+	runningServersOrder  []string
+	socketPtrOffsetMap   map[string]uint
+	runningServersForked bool
+
+	DefaultReadTimeOut    time.Duration
+	DefaultWriteTimeOut   time.Duration
+	DefaultMaxHeaderBytes int
+	DefaultHammerTime     time.Duration
+
+	isChild     bool
+	socketOrder string
+
+	hookableSignals []os.Signal
+)
+
+func init() {
+	flag.BoolVar(&isChild, "continue", false, "listen on open fd (after forking)")
+	flag.StringVar(&socketOrder, "socketorder", "", "previous initialization order - used when more than one listener was started")
+
+	runningServerReg = sync.RWMutex{}
+	runningServers = make(map[string]*endlessServer)
+	runningServersOrder = []string{}
+	socketPtrOffsetMap = make(map[string]uint)
+
+	DefaultMaxHeaderBytes = 0 // use http.DefaultMaxHeaderBytes - which currently is 1 << 20 (1MB)
+
+	// after a restart the parent will finish ongoing requests before
+	// shutting down. set to a negative value to disable
+	DefaultHammerTime = 60 * time.Second
+
+	hookableSignals = []os.Signal{
+		syscall.SIGHUP,
+		syscall.SIGUSR1,
+		syscall.SIGUSR2,
+		syscall.SIGINT,
+		syscall.SIGTERM,
+		syscall.SIGTSTP,
+	}
+}
+
+type endlessServer struct {
+	http.Server
+	EndlessListener  net.Listener
+	SignalHooks      map[int]map[os.Signal][]func()
+	tlsInnerListener *endlessListener
+	wg               sync.WaitGroup
+	sigChan          chan os.Signal
+	isChild          bool
+	state            uint8
+	lock             *sync.RWMutex
+}
+
+/*
+NewServer returns an intialized endlessServer Object. Calling Serve on it will
+actually "start" the server.
+*/
+func NewServer(addr string, handler http.Handler) (srv *endlessServer) {
+	runningServerReg.Lock()
+	defer runningServerReg.Unlock()
+	if !flag.Parsed() {
+		flag.Parse()
+	}
+	if len(socketOrder) > 0 {
+		for i, addr := range strings.Split(socketOrder, ",") {
+			socketPtrOffsetMap[addr] = uint(i)
+		}
+	} else {
+		socketPtrOffsetMap[addr] = uint(len(runningServersOrder))
+	}
+
+	srv = &endlessServer{
+		wg:      sync.WaitGroup{},
+		sigChan: make(chan os.Signal),
+		isChild: isChild,
+		SignalHooks: map[int]map[os.Signal][]func(){
+			PRE_SIGNAL: map[os.Signal][]func(){
+				syscall.SIGHUP:  []func(){},
+				syscall.SIGUSR1: []func(){},
+				syscall.SIGUSR2: []func(){},
+				syscall.SIGINT:  []func(){},
+				syscall.SIGTERM: []func(){},
+				syscall.SIGTSTP: []func(){},
+			},
+			POST_SIGNAL: map[os.Signal][]func(){
+				syscall.SIGHUP:  []func(){},
+				syscall.SIGUSR1: []func(){},
+				syscall.SIGUSR2: []func(){},
+				syscall.SIGINT:  []func(){},
+				syscall.SIGTERM: []func(){},
+				syscall.SIGTSTP: []func(){},
+			},
+		},
+		state: STATE_INIT,
+		lock:  &sync.RWMutex{},
+	}
+
+	srv.Server.Addr = addr
+	srv.Server.ReadTimeout = DefaultReadTimeOut
+	srv.Server.WriteTimeout = DefaultWriteTimeOut
+	srv.Server.MaxHeaderBytes = DefaultMaxHeaderBytes
+	srv.Server.Handler = handler
+
+	runningServersOrder = append(runningServersOrder, addr)
+	runningServers[addr] = srv
+
+	return
+}
+
+/*
+ListenAndServe listens on the TCP network address addr and then calls Serve
+with handler to handle requests on incoming connections. Handler is typically
+nil, in which case the DefaultServeMux is used.
+*/
+func ListenAndServe(addr string, handler http.Handler) error {
+	server := NewServer(addr, handler)
+	return server.ListenAndServe()
+}
+
+/*
+ListenAndServeTLS acts identically to ListenAndServe, except that it expects
+HTTPS connections. Additionally, files containing a certificate and matching
+private key for the server must be provided. If the certificate is signed by a
+certificate authority, the certFile should be the concatenation of the server's
+certificate followed by the CA's certificate.
+*/
+func ListenAndServeTLS(addr string, certFile string, keyFile string, handler http.Handler) error {
+	server := NewServer(addr, handler)
+	return server.ListenAndServeTLS(certFile, keyFile)
+}
+
+func (srv *endlessServer) getState() uint8 {
+	srv.lock.RLock()
+	defer srv.lock.RUnlock()
+
+	return srv.state
+}
+
+func (srv *endlessServer) setState(st uint8) {
+	srv.lock.Lock()
+	defer srv.lock.Unlock()
+
+	srv.state = st
+}
+
+/*
+Serve accepts incoming HTTP connections on the listener l, creating a new
+service goroutine for each. The service goroutines read requests and then call
+handler to reply to them. Handler is typically nil, in which case the
+DefaultServeMux is used.
+
+In addition to the stl Serve behaviour each connection is added to a
+sync.Waitgroup so that all outstanding connections can be served before shutting
+down the server.
+*/
+func (srv *endlessServer) Serve() (err error) {
+	defer log.Println(syscall.Getpid(), "Serve() returning...")
+	srv.setState(STATE_RUNNING)
+	err = srv.Server.Serve(srv.EndlessListener)
+	log.Println(syscall.Getpid(), "Waiting for connections to finish...")
+	srv.wg.Wait()
+	srv.setState(STATE_TERMINATE)
+	return
+}
+
+/*
+ListenAndServe listens on the TCP network address srv.Addr and then calls Serve
+to handle requests on incoming connections. If srv.Addr is blank, ":http" is
+used.
+*/
+func (srv *endlessServer) ListenAndServe() (err error) {
+	addr := srv.Addr
+	if addr == "" {
+		addr = ":http"
+	}
+
+	go srv.handleSignals()
+
+	l, err := srv.getListener(addr)
+	if err != nil {
+		log.Println(err)
+		return
+	}
+
+	srv.EndlessListener = newEndlessListener(l, srv)
+
+	if srv.isChild {
+		syscall.Kill(syscall.Getppid(), syscall.SIGTERM)
+	}
+
+	log.Println(syscall.Getpid(), srv.Addr)
+	return srv.Serve()
+}
+
+/*
+ListenAndServeTLS listens on the TCP network address srv.Addr and then calls
+Serve to handle requests on incoming TLS connections.
+
+Filenames containing a certificate and matching private key for the server must
+be provided. If the certificate is signed by a certificate authority, the
+certFile should be the concatenation of the server's certificate followed by the
+CA's certificate.
+
+If srv.Addr is blank, ":https" is used.
+*/
+func (srv *endlessServer) ListenAndServeTLS(certFile, keyFile string) (err error) {
+	addr := srv.Addr
+	if addr == "" {
+		addr = ":https"
+	}
+
+	config := &tls.Config{}
+	if srv.TLSConfig != nil {
+		*config = *srv.TLSConfig
+	}
+	if config.NextProtos == nil {
+		config.NextProtos = []string{"http/1.1"}
+	}
+
+	config.Certificates = make([]tls.Certificate, 1)
+	config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
+	if err != nil {
+		return
+	}
+
+	go srv.handleSignals()
+
+	l, err := srv.getListener(addr)
+	if err != nil {
+		log.Println(err)
+		return
+	}
+
+	srv.tlsInnerListener = newEndlessListener(l, srv)
+	srv.EndlessListener = tls.NewListener(srv.tlsInnerListener, config)
+
+	if srv.isChild {
+		syscall.Kill(syscall.Getppid(), syscall.SIGTERM)
+	}
+
+	log.Println(syscall.Getpid(), srv.Addr)
+	return srv.Serve()
+}
+
+/*
+getListener either opens a new socket to listen on, or takes the acceptor socket
+it got passed when restarted.
+*/
+func (srv *endlessServer) getListener(laddr string) (l net.Listener, err error) {
+	if srv.isChild {
+		var ptrOffset uint = 0
+		runningServerReg.RLock()
+		defer runningServerReg.RUnlock()
+		if len(socketPtrOffsetMap) > 0 {
+			ptrOffset = socketPtrOffsetMap[laddr]
+			// log.Println("laddr", laddr, "ptr offset", socketPtrOffsetMap[laddr])
+		}
+
+		f := os.NewFile(uintptr(3+ptrOffset), "")
+		l, err = net.FileListener(f)
+		if err != nil {
+			err = fmt.Errorf("net.FileListener error: %v", err)
+			return
+		}
+	} else {
+		l, err = net.Listen("tcp", laddr)
+		if err != nil {
+			err = fmt.Errorf("net.Listen error: %v", err)
+			return
+		}
+	}
+	return
+}
+
+/*
+handleSignals listens for os Signals and calls any hooked in function that the
+user had registered with the signal.
+*/
+func (srv *endlessServer) handleSignals() {
+	var sig os.Signal
+
+	signal.Notify(
+		srv.sigChan,
+		hookableSignals...,
+	)
+
+	pid := syscall.Getpid()
+	for {
+		sig = <-srv.sigChan
+		srv.signalHooks(PRE_SIGNAL, sig)
+		switch sig {
+		case syscall.SIGHUP:
+			log.Println(pid, "Received SIGHUP. forking.")
+			err := srv.fork()
+			if err != nil {
+				log.Println("Fork err:", err)
+			}
+		case syscall.SIGUSR1:
+			log.Println(pid, "Received SIGUSR1.")
+		case syscall.SIGUSR2:
+			log.Println(pid, "Received SIGUSR2.")
+			srv.hammerTime(0 * time.Second)
+		case syscall.SIGINT:
+			log.Println(pid, "Received SIGINT.")
+			srv.shutdown()
+		case syscall.SIGTERM:
+			log.Println(pid, "Received SIGTERM.")
+			srv.shutdown()
+		case syscall.SIGTSTP:
+			log.Println(pid, "Received SIGTSTP.")
+		default:
+			log.Printf("Received %v: nothing i care about...\n", sig)
+		}
+		srv.signalHooks(POST_SIGNAL, sig)
+	}
+}
+
+func (srv *endlessServer) signalHooks(ppFlag int, sig os.Signal) {
+	if _, notSet := srv.SignalHooks[ppFlag][sig]; !notSet {
+		return
+	}
+	for _, f := range srv.SignalHooks[ppFlag][sig] {
+		f()
+	}
+	return
+}
+
+/*
+shutdown closes the listener so that no new connections are accepted. it also
+starts a goroutine that will hammer (stop all running requests) the server
+after DefaultHammerTime.
+*/
+func (srv *endlessServer) shutdown() {
+	if srv.getState() != STATE_RUNNING {
+		return
+	}
+
+	srv.setState(STATE_SHUTTING_DOWN)
+	if DefaultHammerTime >= 0 {
+		go srv.hammerTime(DefaultHammerTime)
+	}
+	// disable keep-alives on existing connections
+	srv.SetKeepAlivesEnabled(false)
+	err := srv.EndlessListener.Close()
+	if err != nil {
+		log.Println(syscall.Getpid(), "Listener.Close() error:", err)
+	} else {
+		log.Println(syscall.Getpid(), srv.EndlessListener.Addr(), "Listener closed.")
+	}
+}
+
+/*
+hammerTime forces the server to shutdown in a given timeout - whether it
+finished outstanding requests or not. if Read/WriteTimeout are not set or the
+max header size is very big a connection could hang...
+
+srv.Serve() will not return until all connections are served. this will
+unblock the srv.wg.Wait() in Serve() thus causing ListenAndServe(TLS) to
+return.
+*/
+func (srv *endlessServer) hammerTime(d time.Duration) {
+	defer func() {
+		// we are calling srv.wg.Done() until it panics which means we called
+		// Done() when the counter was already at 0 and we're done.
+		// (and thus Serve() will return and the parent will exit)
+		if r := recover(); r != nil {
+			log.Println("WaitGroup at 0", r)
+		}
+	}()
+	if srv.getState() != STATE_SHUTTING_DOWN {
+		return
+	}
+	time.Sleep(d)
+	log.Println("[STOP - Hammer Time] Forcefully shutting down parent")
+	for {
+		if srv.getState() == STATE_TERMINATE {
+			break
+		}
+		srv.wg.Done()
+		runtime.Gosched()
+	}
+}
+
+func (srv *endlessServer) fork() (err error) {
+	runningServerReg.Lock()
+	defer runningServerReg.Unlock()
+	
+	// only one server isntance should fork!
+	if runningServersForked {
+		return errors.New("Another process already forked. Ignoring this one.")
+	}
+
+	runningServersForked = true
+
+	var files = make([]*os.File, len(runningServers))
+	var orderArgs = make([]string, len(runningServers))
+	// get the accessor socket fds for _all_ server instances
+	for _, srvPtr := range runningServers {
+		// introspect.PrintTypeDump(srvPtr.EndlessListener)
+		switch srvPtr.EndlessListener.(type) {
+		case *endlessListener:
+			// normal listener
+			files[socketPtrOffsetMap[srvPtr.Server.Addr]] = srvPtr.EndlessListener.(*endlessListener).File()
+		default:
+			// tls listener
+			files[socketPtrOffsetMap[srvPtr.Server.Addr]] = srvPtr.tlsInnerListener.File()
+		}
+		orderArgs[socketPtrOffsetMap[srvPtr.Server.Addr]] = srvPtr.Server.Addr
+	}
+
+	// log.Println(files)
+	path := os.Args[0]
+	var args []string
+	if len(os.Args) > 1 {
+		for _, arg := range os.Args[1:] {
+			if arg == "-continue" {
+				break
+			}
+			args = append(args, arg)
+		}
+	}
+	args = append(args, "-continue")
+	if len(runningServers) > 1 {
+		args = append(args, fmt.Sprintf(`-socketorder=%s`, strings.Join(orderArgs, ",")))
+		// log.Println(args)
+	}
+
+	cmd := exec.Command(path, args...)
+	cmd.Stdout = os.Stdout
+	cmd.Stderr = os.Stderr
+	cmd.ExtraFiles = files
+	// cmd.SysProcAttr = &syscall.SysProcAttr{
+	// 	Setsid:  true,
+	// 	Setctty: true,
+	// 	Ctty:    ,
+	// }
+
+	err = cmd.Start()
+	if err != nil {
+		log.Fatalf("Restart: Failed to launch, error: %v", err)
+	}
+
+	return
+}
+
+type endlessListener struct {
+	net.Listener
+	stopped bool
+	server  *endlessServer
+}
+
+func (el *endlessListener) Accept() (c net.Conn, err error) {
+	tc, err := el.Listener.(*net.TCPListener).AcceptTCP()
+	if err != nil {
+		return
+	}
+
+	tc.SetKeepAlive(true)                  // see http.tcpKeepAliveListener
+	tc.SetKeepAlivePeriod(3 * time.Minute) // see http.tcpKeepAliveListener
+
+	c = endlessConn{
+		Conn:   tc,
+		server: el.server,
+	}
+
+	el.server.wg.Add(1)
+	return
+}
+
+func newEndlessListener(l net.Listener, srv *endlessServer) (el *endlessListener) {
+	el = &endlessListener{
+		Listener: l,
+		server:   srv,
+	}
+
+	return
+}
+
+func (el *endlessListener) Close() error {
+	if el.stopped {
+		return syscall.EINVAL
+	}
+
+	el.stopped = true
+	return el.Listener.Close()
+}
+
+func (el *endlessListener) File() *os.File {
+	// returns a dup(2) - FD_CLOEXEC flag *not* set
+	tl := el.Listener.(*net.TCPListener)
+	fl, _ := tl.File()
+	return fl
+}
+
+type endlessConn struct {
+	net.Conn
+	server *endlessServer
+}
+
+func (w endlessConn) Close() error {
+	err := w.Conn.Close()
+	if err == nil {
+		w.server.wg.Done()
+	}
+	return err
+}
+
+/*
+RegisterSignalHook registers a function to be run PRE_SIGNAL or POST_SIGNAL for
+a given signal. PRE or POST in this case means before or after the signal
+related code endless itself runs
+*/
+func (srv *endlessServer) RegisterSignalHook(prePost int, sig os.Signal, f func()) (err error) {
+	if prePost != PRE_SIGNAL && prePost != POST_SIGNAL {
+		err = fmt.Errorf("Cannot use %v for prePost arg. Must be endless.PRE_SIGNAL or endless.POST_SIGNAL.")
+		return
+	}
+	for _, s := range hookableSignals {
+		if s == sig {
+			srv.SignalHooks[prePost][sig] = append(srv.SignalHooks[prePost][sig], f)
+			return
+		}
+	}
+	err = fmt.Errorf("Signal %v is not supported.")
+	return
+}

+ 4 - 4
weixin/src/main.go

@@ -1,9 +1,9 @@
 package main
 
 import (
-	//"endless"
+	"endless"
 	"log"
-	"net/http"
+	//"net/http"
 	"qfw/util"
 	"qfw/util/elastic"
 	"qfw/util/mongodb"
@@ -37,6 +37,6 @@ func main() {
 	//启动Rpc服务
 	rpc.StartWeixinRpc(weixin.Mux)
 	//启动web服务
-	http.ListenAndServe(":"+wf.SysConfig.Port, nil) // 启动接收微信数据服务器
-	//endless.ListenAndServe(":"+wf.SysConfig.Port, nil)
+	//http.ListenAndServe(":"+wf.SysConfig.Port, nil) // 启动接收微信数据服务器
+	endless.ListenAndServe(":"+wf.SysConfig.Port, nil)
 }

+ 1 - 1
weixin/src/qfw/weixin/msgtxtchandler.go

@@ -4,7 +4,7 @@ import (
 	"encoding/json"
 	"fmt"
 	"io/ioutil"
-	"log"
+	_ "log"
 	"math/rand"
 	"net"
 	"net/http"