package main
import (
"net/http"
log "github.com/sirupsen/logrus"
"io/ioutil"
"fmt"
"bytes"
"sync"
_"time"
)
func main() {
var wg sync.WaitGroup
var count int
var rw sync.RWMutex
TEST:
for i := 0; i < 1; i++ {
wg.Add(1)
go func () {
defer wg.Done()
tr := http.Transport{DisableKeepAlives: false}
client := &http.Client{Transport: &tr}
for {
f, err := ioutil.ReadFile("data")
if err != nil {
fmt.Println("read file err", err)
return
}
fmt.Println(len(f))
reader := bytes.NewReader(f)
rw.Lock()
count += 1
index := count
rw.Unlock()
resp, err := client.Post("http://0.0.0.0:8888", "application/x-www-form-urlencoded", reader)
if err != nil {
rw.RLock()
currentCount := count
rw.RUnlock()
log.Fatal(err, index, currentCount)
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
log.Printf("data[%s]", string(data))
// time.Sleep(time.Second)
}
}()
}
wg.Wait()
goto TEST
}复制代码
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"time"
"context"
)
type myHandler struct {
}
func (h myHandler)ServeHTTP(w http.ResponseWriter, r *http.Request) {
//print header
// fmt.Println("header", r.Header)
//debug body
_, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Println("read body error", err)
io.WriteString(w, "read you body error!")
return
}
// fmt.Println("data len", len(data))
io.WriteString(w, "goad it")
return
}
func main() {
// http.HandleFunc("/", myHandler)
// err := http.ListenAndServe("0.0.0.0:8888", nil)
// if err != nil {
// fmt.Println("ListenAndServe error", err)
// return
// }
server := &http.Server {
Addr: "0.0.0.0:8888",
Handler: myHandler{},
}
d := time.Duration(time.Second*10)
t := time.NewTimer(d)
defer t.Stop()
go func (){
<- t.C
shutdown(server)
}()
server.ListenAndServe()
for {
fmt.Println(1)
time.Sleep(time.Second)
}
fmt.Println(2)
return
}
func shutdown(server *http.Server) {
ctx, cancel := context.WithTimeout(context.TODO(), 3600)
defer cancel()
server.Shutdown(ctx)
}
复制代码
func (s *Server) doKeepAlives() bool { return atomic.LoadInt32(&s.disableKeepAlives) == 0 && !s.shuttingDown()}func (s *Server) shuttingDown() bool { return atomic.LoadInt32(&s.inShutdown) != 0}复制代码
//在go1.10 net/http/server.go 1845行 if !w.conn.server.doKeepAlives() { // We're in shutdown mode. We might've replied // to the user without "Connection: close" and // they might think they can send another // request, but such is life with HTTP/1.1. return }复制代码
复制代码
因此在怀疑close的方式致使出现这种状况,因此针对长链接,若是客户端持续的发送数据可能会出现这种状况。git
为了验证下,我改了closeIdles的代码,改为了只关闭服务端的写,让客户端能把数据发送过来github
稳定是有四次挥手的,可是客户端仍是收到了EOF,服务端不是优雅的。app
再改动下,让shutdown退出以前sleep了500毫秒tcp
红色的RST忽略,那是客户端发起的从新链接测试
因此初步结论就是server没法作到真正的graceful。ui