docker stop {這陣子的練習go的container ID}
複製一份這個container環境當一個image
docker commit {這陣子的練習go的container ID} {新環境image名稱}
先到go path路徑底下
讓$PWD指向go path
cd /var/go1
run from the commited image
docker run --name go-test -v $PWD:/var/go1/ -it -d -p 3001:3001 {新環境image名稱}
ok了 新container附帶3001 port開啟
main.go
package main
import (
"fmt"
"log"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "I love %s!", r.URL.Path[1:])
}
func main() {
http.HandleFunc("/", handler)
log.Println("http server run on 3001 port")
log.Fatal(http.ListenAndServe(":3001", nil))
}
利用curl 去訪查3001 port
curl http://{ip}:3001/gogogo
實作flag 有關port cli
package main
import (
"flag"
"fmt"
"log"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "I love %s!", r.URL.Path[1:])
}
func main() {
var port string
flag.StringVar(&port, "port", "3001", "server port")
flag.StringVar(&port, "p", "3001", "server port")
flag.Parse()
http.HandleFunc("/", handler)
log.Println("http server run on " + port + " port")
log.Fatal(http.ListenAndServe(":"+port, nil))
}
下查詢
go run main.go -h
出現我們設定的flag說明
測試flag
go run main.go -p 1234
如果要port=XXX型式
func main() {
var port string
flag.StringVar(&port, "port", "3001", "server port")
flag.StringVar(&port, "p", "3001", "server port")
flag.Parse()
if p, ok := os.LookupEnv("PORT"); ok {
port = p
}
http.HandleFunc("/", handler)
log.Println("http server run on " + port + " port")
log.Fatal(http.ListenAndServe(":"+port, nil))
}
即可