zoukankan      html  css  js  c++  java
  • golang中关闭http server

    golange 开启http server 服务之后,怎么关闭呢?

    -----------------------------------------------------------------------------------------------------

    这个也不错: http://blog.csdn.net/codyguo/article/details/54582453

    package main
    
    import (
        "log"
        "io"
        "time"
        "net/http"
    )
    
    func startHttpServer() *http.Server {
        srv := &http.Server{Addr: ":8080"}
    
        http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            io.WriteString(w, "hello world
    ")
        })
    
        go func() {
            if err := srv.ListenAndServe(); err != nil {
                // cannot panic, because this probably is an intentional close
                log.Printf("Httpserver: ListenAndServe() error: %s", err)
            }
        }()
    
        // returning reference so caller can call Shutdown()
        return srv
    }
    
    func main() {
        log.Printf("main: starting HTTP server")
    
        srv := startHttpServer()
    
        log.Printf("main: serving for 10 seconds")
    
        time.Sleep(10 * time.Second)
    
        log.Printf("main: stopping HTTP server")
    
        // now close the server gracefully ("shutdown")
        // timeout could be given instead of nil as a https://golang.org/pkg/context/
        if err := srv.Shutdown(nil); err != nil {
            panic(err) // failure/timeout shutting down the server gracefully
        }
    
        log.Printf("main: done. exiting")
    }
  • 相关阅读:
    拷贝构造函数与赋值函数的区别
    C++模板(一)
    拷贝构造函数
    memcpy函数
    malloc calloc 和 realloc
    extern关键字
    C中不安全函数
    缓冲区溢出问题
    C++引用
    背包问题专栏(01,完全,多重)
  • 原文地址:https://www.cnblogs.com/oxspirt/p/7058812.html
Copyright © 2011-2022 走看看