iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 20
0
自我挑戰組

Go to 放棄系列 第 20

go note => existing docker set port and go flag

  • 分享至 

  • xImage
  •  
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開啟

go flag

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

https://ithelp.ithome.com.tw/upload/images/20181104/201124771GqpQEhWza.png

實作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說明
https://ithelp.ithome.com.tw/upload/images/20181104/20112477gkLjPlOOom.png
測試flag

go run main.go -p 1234

https://ithelp.ithome.com.tw/upload/images/20181104/20112477kddFzbUSJC.png

如果要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))
}

即可
https://ithelp.ithome.com.tw/upload/images/20181104/20112477Wu7wBq9sHw.png


上一篇
go note => goroutine
下一篇
go note => go docker health check
系列文
Go to 放棄30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言