Skip to content

Instantly share code, notes, and snippets.

@lucatironi
Last active July 24, 2016 21:12
Show Gist options
  • Save lucatironi/428080356cb6bdfa5147e6016f340ec7 to your computer and use it in GitHub Desktop.
Save lucatironi/428080356cb6bdfa5147e6016f340ec7 to your computer and use it in GitHub Desktop.
GO Basic Microservice

Usage

  git clone https://gist.github.com/428080356cb6bdfa5147e6016f340ec7.git
  docker-compose build
  docker-compose up
api:
container_name: app
build: ./
ports:
- 8080:8080
volumes:
- ./:/go/src/github.com/lucatironi/hello
FROM golang:onbuild
EXPOSE 8080
package main
import (
"encoding/json"
"log"
"net/http"
"time"
)
func Logger(inner http.HandlerFunc, name string) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner.ServeHTTP(w, r)
log.Printf(
"%s\t%s\t%s\t%s",
r.Method,
r.RequestURI,
name,
time.Since(start),
)
})
}
type HealthCheckStatus struct {
Status string `json:"status"`
}
func HealthCheckHandler(w http.ResponseWriter, r *http.Request) {
message := HealthCheckStatus{"OK"}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(message); err != nil {
panic(err)
}
}
func main() {
http.HandleFunc("/", Logger(HealthCheckHandler, "health#check"))
log.Printf("Service listening on port 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
func TestHealthCheckHandler(t *testing.T) {
req, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatal(err)
}
rec := httptest.NewRecorder()
handler := http.HandlerFunc(HealthCheckHandler)
handler.ServeHTTP(rec, req)
expectedStatusCode := http.StatusOK
if statusCode := rec.Code; statusCode != expectedStatusCode {
t.Errorf("handler returned wrong status code: got %v want %v",
statusCode, expectedStatusCode)
}
expectedContentType := "application/json; charset=UTF-8"
if contentType := rec.Header().Get("Content-Type"); contentType != expectedContentType {
t.Errorf("handler returned wrong Content-Type: got %v want %v",
contentType, expectedContentType)
}
var body HealthCheckStatus
json.Unmarshal(rec.Body.Bytes(), &body)
expectedBody := HealthCheckStatus{"OK"}
if body != expectedBody {
t.Errorf("handler returned unexpected body: got `%v` want `%v`",
body, expectedBody)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment