實作ping flag
package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
)
func handler(w http.ResponseWriter, r *http.Request) {
log.Println("http request!!!!")
fmt.Fprintf(w, "I love %s!", r.URL.Path[1:])
}
func pinger(port string) error {
resp, err := http.Get("http://172.20.10.10:" + port)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("server returned not 200 status code")
}
return nil
}
func main() {
var port string
var ping bool
flag.StringVar(&port, "port", "3001", "server port")
flag.StringVar(&port, "p", "3001", "server port")
flag.BoolVar(&ping, "ping", false, "check server live")
flag.Parse()
if p, ok := os.LookupEnv("PORT"); ok {
port = p
}
if ping {
if err := pinger(port); err != nil {
log.Printf("ping server error: %v\n ", err)
}
return // 就不會執行下面的http handler
}
http.HandleFunc("/", handler)
log.Println("http server run on " + port + " port")
log.Fatal(http.ListenAndServe(":"+port, nil))
}
開啟另外一個terminal 並下command run起3001 port
go run main.go -p 3001
另一個terminal 就針對3001 port ping
go run main.go -p 3001 -ping
可以看到第一個terminal有被執行到handler.裡頭有個log被觸發
剩餘的 明日再研究