使用docker运行自己的第一个golang项目

# docker pull golang

# mkdir golang && vim main.go

package main
import (
    "context"
    "fmt"
    "log"
    "net/http"
    "os"
    "os/signal"
    "syscall"
)


func main() {

    mux := http.NewServeMux()

    mux.Handle(“/”, &helloHandler{})

    server := &http.Server{

        Addr:    “:8080”,

        Handler: mux,

    }

    // 创建系统信号接收器

    done := make(chan os.Signal)

    signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)

    go func() {

        <-done

        if err := server.Shutdown(context.Background()); err != nil {

            log.Fatal(“Shutdown server:”, err)

        }

    }()

    log.Println(“Starting HTTP server…”)

    err := server.ListenAndServe()

    if err != nil {

        if err == http.ErrServerClosed {

            log.Print(“Server closed under request”)

        } else {

            log.Fatal(“Server closed unexpected”)

        }

    }

}

type helloHandler struct{}

func (*helloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    fmt.Fprintf(w, “Hello World”)

}

# docker run –rm -it –name go-http-demo -v $PWD:/go/src/example.com/go-http-demo  -p 8000:8080 golang

root@9c3b8c8d9051:/go# cd /go/src/example.com/go-http-demo/
root@9c3b8c8d9051:/go/src/example.com/go-http-demo# ls
main.go
root@9c3b8c8d9051:/go/src/example.com/go-http-demo# go run main.go
2021/01/12 13:18:10 Starting HTTP server...

访问8000端口预览效果

发表评论

电子邮件地址不会被公开。 必填项已用*标注