文章首发于:clawhub.club
直接贴代码:
注释已经写的很清楚了,如果感兴趣可以去github上看整个工程
https://github.com/ClawHub/go-study
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| package http
import ( "context" "fmt" "go-study/src/log" "net/http" "os" "os/signal" "syscall" "time" )
func DemoHttp() { log.HttpLogger.Info("-------------http-------------") startWebService("", "9997", "", "", false) }
func startWebService(host, port, certFile, keyFile string, enableSSL bool) { log.HttpLogger.Info("http server starting......")
http.HandleFunc("/welcome", welcome)
hostPort := host + ":" + port server := &http.Server{ Addr: hostPort, Handler: http.DefaultServeMux, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } go func() { var err error if enableSSL { err = server.ListenAndServeTLS(certFile, keyFile) } else { err = server.ListenAndServe() } if err == nil { log.HttpLogger.Info(fmt.Sprintf("success to bind %s", hostPort)) } else { log.HttpLogger.Info(fmt.Sprintf("fail to bind %s %s", hostPort, err)) } }() signalChannel := make(chan os.Signal) signal.Notify(signalChannel, syscall.SIGINT, syscall.SIGTERM) <-signalChannel err := server.Shutdown(context.Background()) if err != nil { log.HttpLogger.Error("server shutdown fail") } log.HttpLogger.Info("http server closing......") }
func welcome(rw http.ResponseWriter, req *http.Request) { _, _ = fmt.Fprintln(rw, "welcome") }
|