请大家教个GO问题呢,我在协程启动http监听服务(http.ListenAndServe),并且在协程中调用Close停止服务。然后整个程序都退出了。有没有办法停用http服务后让入口main函数继续执行呢?

colin_86 发布于 08/05 15:32
阅读 177
收藏 0

开源之夏第三届火热来袭,高校学生参与赢万元奖金!>>>

请大家教个问题呢,我在协程启动http监听服务(http.ListenAndServe),并且在协程中调用Close停止服务。然后整个程序都退出了。有没有办法停用http服务后让入口main函数继续执行呢?code如下:

package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"time"
)

var addr = flag.String("addr", ":8080", "http service address")
var actionsWsStartChannel = make(chan bool)
var MainQuit = make(chan bool)

func main() {
	go func() {
		http.HandleFunc("/", serveHome)
		server := &http.Server{Addr: *addr}
		go func() {
			err := server.ListenAndServe()
			if err != nil {
				log.Fatal("ListenAndServe: ", err)
			}
		}()

		for {
			select {
			case v := <-actionsWsStartChannel:
				if v == true {
					// go server.ListenAndServe()
					// fmt.Println("start")
				} else {
					server.Close()
					fmt.Println("http stop")
					return
				}
			}
		}
	}()

	go func() {
		select {
		case <-time.After(10 * time.Second):
			actionsWsStartChannel <- false
		}
	}()

	go func() {
		select {
		case <-time.After(30 * time.Second):
			MainQuit <- true
		}
	}()

	for {
		select {
		case <-MainQuit:
			fmt.Println("main quit")
			return
		}
	}
}

func serveHome(w http.ResponseWriter, r *http.Request) {
	log.Println(r.URL)
	if r.URL.Path != "/" {
		http.Error(w, "Not found", http.StatusNotFound)
		return
	}
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}
	http.ServeFile(w, r, "home.html")
}
go version go1.17.2 windows/amd64

 

加载中
0
c
colin_86

此行代码导致:

log.Fatal("ListenAndServe: ", err)

 

0
c
colin_86

求解答,感谢大家

OSCHINA
登录后可查看更多优质内容
返回顶部
顶部