Golang Go语言中请教 HTTP 的 Shutdown 函数

Golang Go语言中请教 HTTP 的 Shutdown 函数

server.Shutdown 也会直接中断正在发数据的连接吗?

不 Shutdown 的话正常应该发送 60 个 asd,我在第 5 个调用了 Shutdown,连接直接被中断了。

请问一下大家这个是怎么回事?

var server *http.Server
server = &http.Server{
	IdleTimeout: 60*time.Second,
	WriteTimeout: 60*time.Second,
	Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Length", "181")
		w.WriteHeader(200)
		for i := 0; i < 60; i++ {
			if i == 5 {
				//server.SetKeepAlivesEnabled(false)
				_, _ = w.Write([]byte("zxc"))
				fmt.Println(server.Shutdown(context.Background()))
				_, _ = w.Write([]byte("qwe"))
			}
			_, _ = w.Write([]byte("asd"))
			if flusher, ok := w.( http.Flusher); ok {
				flusher.Flush()
			} else {
				fmt.Println("Not flushable")
			}
			//time.Sleep(time.Second)
		}
		_, _ = w.Write([]byte("\n"))
	}),
}
err = server.Serve(ServeHTTP)
fmt.Println(err)

$ telnet 127.0.0.1 80
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
GET / HTTP/1.1
Host: 127.0.0.1

HTTP/1.1 200 OK
Content-Length: 181
Date: Mon, 29 Apr 2019 15:14:18 GMT
Content-Type: text/plain; charset=utf-8

asdasdasdasdasdConnection closed by foreign host.

更多关于Golang Go语言中请教 HTTP 的 Shutdown 函数的实战教程也可以访问 https://www.itying.com/category-94-b0.html

4 回复

https://golang.org/pkg/net/http/#Server.Shutdown

When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return ErrServerClosed. Make sure the program doesn’t exit and waits instead for Shutdown to return.

更多关于Golang Go语言中请教 HTTP 的 Shutdown 函数的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


// Shutdown works by first closing all open
// listeners, then closing all idle connections, and then waiting
// indefinitely for connections to return to idle and then shut down.

补充楼上,waiting indefinitely.

非常感谢,加一个 chan 等一下就好了,成功了

在 Go 语言中,http.Server 结构体的 Shutdown 方法是用于优雅地关闭 HTTP 服务器的。当你需要关闭服务器时,调用这个方法会停止接受新的连接,并等待当前正在处理的请求完成。这对于需要维护服务可用性和数据一致性的应用来说非常重要。

以下是 Shutdown 方法的一些关键点和使用示例:

  1. 停止接受新连接:调用 Shutdown 后,服务器将不再接受新的连接请求。

  2. 等待活动请求完成:服务器会继续处理已经建立的连接和正在进行的请求,直到它们完成。

  3. 超时控制Shutdown 方法接受一个 context.Context 参数,用于控制等待活动请求完成的最长时间。如果在这个时间内所有请求都未完成,服务器将强制关闭这些连接。

示例代码:

package main

import (
    "context"
    "fmt"
    "net/http"
    "time"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello, World!")
}

func main() {
    server := &http.Server{Addr: ":8080", Handler: http.HandlerFunc(helloHandler)}
    go func() {
        if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
            fmt.Println("ListenAndServe error:", err)
        }
    }()

    // Simulate a graceful shutdown after 5 seconds
    time.Sleep(5 * time.Second)
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    server.Shutdown(ctx)
    fmt.Println("Server gracefully stopped")
}

这段代码启动了一个简单的 HTTP 服务器,并在 5 秒后优雅地关闭它。

回到顶部