บันทึกไว้กันลืม Basic Golang ( Docker )


Create main.go

  • create function main > using gorilla/mux for router
...
func main() {
	r := mux.NewRouter()
	r.HandleFunc("/", hello)

	log.Println("listen port :1234")
	http.ListenAndServe(":1234", r)
}
  • create function hello
func hello(w http.ResponseWriter, r *http.Request) {
	data := map[string]string{
		"message": "Hello",
	}

	json.NewEncoder(w).Encode(&data)
}

package main

import (
	"encoding/json"
	"log"
	"net/http"

	"github.com/gorilla/mux"
)

func hello(w http.ResponseWriter, r *http.Request) {
	data := map[string]string{
		"message": "Hello",
	}

	json.NewEncoder(w).Encode(&data)
}

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/", hello).Methods(http.MethodGet)

	log.Println("listen port :1234")
	http.ListenAndServe(":1234", r)
}


Create Dockerfile

FROM golang:latest 
RUN mkdir /app 
ADD . /app/ 
WORKDIR /app 
RUN go mod init demo
RUN go build -o main . 
CMD ["/app/main"]

Build & Run

$ docker build -t demo-go .
$ docker run -p 1234:1234 demo-go .
...
2020/05/14 13:21:33 listen port :1234

ทดสอบ curl

$ curl localhost:1234
...
{"message":"Hello"}