Monday, June 18, 2018

Running Gorilla/Mux in Docker

0 lượt xem comment 0 comments

Go is a very simple and powerful language. I like Go.Go performance is amazing. I don't like that Go don't have proper Generics and Exceptions but besides that is all great. Go is great for DevOps because go generate a simple binary that is executable and this is really awesome.
Today I want to show to build a simple counter service using Go, Gorilla/Mux and Docker. Gorilla/Mux is a simple HTTP Router for Go. Using native JSON support from Go + Mux you can build some simple and yet powerful services.
We will use sync/atomic in order to make sure if we have a code that is threadsafe.  You will need to have Go and Docker installed in your machine.  We will use Go language version 1.10 and latest Gorilla/Mux. Let's get started!




The Dockerfile

FROM golang:1.10
WORKDIR /
COPY . .
RUN go get -d github.com/gorilla/mux
CMD ["go","run","main.go"]
view raw Dockerfile hosted with ❤ by GitHub

Here we are using Go 1.10 docker image as the image. We are using to get in order to install gorilla/mux. Now we can build the docker image. We just need to run the command: $ docker run diegopacheco/go-counter.

Go Code

Go code is so simple. Here we create a router and add a simple route to "/" path. We will run the server on port 8080. As you can see here we are using sync/atomic in order to create a thread-safe integer. We are using the method atomic.AddUint64 in order to safe increment it.  This is done the function called Counter. Which just get the integer and increment and return.

package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"sync/atomic"
"github.com/gorilla/mux"
)
var counter uint64
func main() {
atomic.AddUint64(&counter, 0)
router := mux.NewRouter()
router.HandleFunc("/", Counter).Methods("GET")
fmt.Println("GO REST server running on http://localhost:8080 ")
log.Fatal(http.ListenAndServe(":8080", router))
}
// Counter increments and get the number of users who hit the pahge
func Counter(w http.ResponseWriter, r *http.Request) {
atomic.AddUint64(&counter, 1)
json.NewEncoder(w).Encode(counter)
}
view raw main.go hosted with ❤ by GitHub

Now we can run this docker by doing: $ docker run diegopacheco/go-counter then you can go to your browser and see the counter working :D

That's it. You can get the whole code here. As you can see go is simple and object which very few lines of code we can do a lot.

Cheers,
Diego Pacheco
Tags: code,

comment 0 comments

Chuyên mục văn hoá giải trí của VnExpress

.

© 2017 www.blogthuthuatwin10.com

Tầng 5, Tòa nhà FPT Cầu Giấy, phố Duy Tân, Phường Dịch Vọng Hậu, Quận Cầu Giấy, Hà Nội
Email: nguyenanhtuan2401@gmail.com
Điện thoại: 0908 562 750 ext 4548; Liên hệ quảng cáo: 4567.