16 Commits

9 changed files with 222 additions and 18 deletions

41
.golangci.toml Normal file
View File

@ -0,0 +1,41 @@
[run]
deadline = "2m"
skip-files = []
[linters-settings]
[linters-settings.govet]
check-shadowing = true
[linters-settings.gocyclo]
min-complexity = 12.0
[linters-settings.maligned]
suggest-new = true
[linters-settings.goconst]
min-len = 3.0
min-occurrences = 3.0
[linters-settings.misspell]
locale = "US"
[linters]
enable-all = true
disable = [
"maligned",
"lll",
"gosec",
"dupl",
"prealloc",
"gochecknoglobals",
"gochecknoinits",
"gomnd",
"wsl",
]
[issues]
exclude-use-default = false
max-per-linter = 0
max-same-issues = 0
exclude = []

53
.travis.yml Normal file
View File

@ -0,0 +1,53 @@
language: go
go:
- "1.x"
cache:
directories:
- $GOPATH/pkg/mod
branches:
only:
- master
- /^v\d+\.\d+(\.\d+)?(-\S*)?$/
notifications:
email:
on_success: never
on_failure: change
env:
- GO111MODULE=on
before_install:
# Install linters and misspell
- curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | bash -s -- -b $GOPATH/bin ${GOLANGCI_LINT_VERSION}
- golangci-lint --version
# Install Docker image multi-arch builder
- curl -sfL https://raw.githubusercontent.com/ldez/seihon/master/godownloader.sh | bash -s -- -b "${GOPATH}/bin" ${SEIHON_VERSION}
- seihon --version
install:
- go mod tidy
- git diff --exit-code go.mod
- git diff --exit-code go.sum
- go mod download
script:
- make
- make image
before_deploy:
- >
if ! [ "$BEFORE_DEPLOY_RUN" ]; then
export BEFORE_DEPLOY_RUN=1;
echo "${DOCKER_PASSWORD}" | docker login -u "${DOCKER_USERNAME}" --password-stdin
fi
deploy:
- provider: script
skip_cleanup: true
script: make publish-images
on:
tags: true

View File

@ -1,10 +1,26 @@
FROM golang:1.11 as builder FROM golang:1-alpine as builder
RUN apk --no-cache --no-progress add git ca-certificates tzdata make \
&& update-ca-certificates \
&& rm -rf /var/cache/apk/*
WORKDIR /go/whoami WORKDIR /go/whoami
# Download go modules
COPY go.mod .
COPY go.sum .
RUN GO111MODULE=on GOPROXY=https://proxy.golang.org go mod download
COPY . . COPY . .
RUN make build RUN make build
# Create a minimal container to run a Golang static binary # Create a minimal container to run a Golang static binary
FROM scratch FROM scratch
COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /go/whoami/whoami . COPY --from=builder /go/whoami/whoami .
ENTRYPOINT ["/whoami"] ENTRYPOINT ["/whoami"]
EXPOSE 80 EXPOSE 80

View File

@ -1,12 +1,20 @@
.PHONY: default build dependencies image .PHONY: default build image check publish-images
default: build TAG_NAME := $(shell git tag -l --contains HEAD)
default: check test build
test:
go test -v -cover ./...
build: build:
CGO_ENABLED=0 go build -a --installsuffix cgo --ldflags="-s" -o whoami CGO_ENABLED=0 go build -a --installsuffix cgo --ldflags="-s" -o whoami
dependencies:
go mod download
image: image:
docker build -t containous/whoami . docker build -t containous/whoami .
check:
golangci-lint run
publish-images:
seihon publish -v "$(TAG_NAME)" -v "latest" --image-name containous/whoami --dry-run=false

View File

@ -1,13 +1,38 @@
# whoami # whoami
[![Docker Pulls](https://img.shields.io/docker/pulls/containous/whoami.svg)](https://hub.docker.com/r/containous/whoami/) [![Docker Pulls](https://img.shields.io/docker/pulls/containous/whoami.svg)](https://hub.docker.com/r/containous/whoami/)
[![Build Status](https://travis-ci.com/containous/whoami.svg?branch=master)](https://travis-ci.com/containous/whoami)
Tiny Go webserver that prints os information and HTTP request to output Tiny Go webserver that prints os information and HTTP request to output
## Usage
### Paths
- `/data?size=n[&unit=u]`: creates a response with a size `n`. The unit of measure, if specified, accepts the following values: `KB`, `MB`, `GB`, `TB` (optional, default: bytes).
- `/echo`: webSocket echo.
- `/bench`: always return the same response (`1`).
- `/[?wait=d]`: returns the whoami information (request and network information). The optional `wait` query parameter can be provided to tell the server to wait before sending the response. The duration is expected in Go's [`time.Duration`](https://golang.org/pkg/time/#ParseDuration) format (e.g. `/?wait=100ms` to wait 100 milliseconds).
- `/api`: returns the whoami information as JSON.
- `/health`: heath check
- `GET`, `HEAD`, ...: returns a response with the status code defined by the `POST`
- `POST`: changes the status code of the `GET` (`HEAD`, ...) response.
### Flags
- `cert`: give me a certificate.
- `key`: give me a key.
- `port`: give me a port number. (default: 80)
- `name`: give me a name. (it can be also defined with `WHOAMI_NAME` environment variable)
## Examples
```console ```console
$ docker run -d -P --name iamfoo containous/whoami $ docker run -d -P --name iamfoo containous/whoami
$ docker inspect --format '{{ .NetworkSettings.Ports }}' iamfoo $ docker inspect --format '{{ .NetworkSettings.Ports }}' iamfoo
map[80/tcp:[{0.0.0.0 32769}]] map[80/tcp:[{0.0.0.0 32769}]]
$ curl "http://0.0.0.0:32769" $ curl "http://0.0.0.0:32769"
Hostname : 6e0030e67d6a Hostname : 6e0030e67d6a
IP : 127.0.0.1 IP : 127.0.0.1
@ -19,3 +44,27 @@ Host: 0.0.0.0:32769
User-Agent: curl/7.35.0 User-Agent: curl/7.35.0
Accept: */* Accept: */*
``` ```
```console
# updates health check status
$ curl -X POST -d '500' http://localhost:80/health
# calls the health check
$ curl -v http://localhost:80/health
* Trying ::1:80...
* TCP_NODELAY set
* Connected to localhost (::1) port 80 (#0)
> GET /health HTTP/1.1
> Host: localhost:80
> User-Agent: curl/7.65.3
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 500 Internal Server Error
< Date: Mon, 16 Sep 2019 22:52:40 GMT
< Content-Length: 0
```
```console
docker run -d -P -v ./certs:/certs --name iamfoo containous/whoami --cert /certs/cert.cer --key /certs/key.key
```

27
app.go
View File

@ -19,6 +19,7 @@ import (
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
) )
// Units
const ( const (
_ = iota _ = iota
KB int64 = 1 << (10 * iota) KB int64 = 1 << (10 * iota)
@ -30,11 +31,13 @@ const (
var cert string var cert string
var key string var key string
var port string var port string
var name string
func init() { func init() {
flag.StringVar(&cert, "cert", "", "give me a certificate") flag.StringVar(&cert, "cert", "", "give me a certificate")
flag.StringVar(&key, "key", "", "give me a key") flag.StringVar(&key, "key", "", "give me a key")
flag.StringVar(&port, "port", "80", "give me a port number") flag.StringVar(&port, "port", "80", "give me a port number")
flag.StringVar(&name, "name", os.Getenv("WHOAMI_NAME"), "give me a name")
} }
var upgrader = websocket.Upgrader{ var upgrader = websocket.Upgrader{
@ -63,7 +66,7 @@ func main() {
func benchHandler(w http.ResponseWriter, _ *http.Request) { func benchHandler(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Connection", "keep-alive") w.Header().Set("Connection", "keep-alive")
w.Header().Set("Content-Type", "text/plain") w.Header().Set("Content-Type", "text/plain")
fmt.Fprint(w, "1") _, _ = fmt.Fprint(w, "1")
} }
func echoHandler(w http.ResponseWriter, r *http.Request) { func echoHandler(w http.ResponseWriter, r *http.Request) {
@ -110,13 +113,13 @@ func dataHandler(w http.ResponseWriter, r *http.Request) {
unit := queryParams.Get("unit") unit := queryParams.Get("unit")
switch strings.ToLower(unit) { switch strings.ToLower(unit) {
case "kb": case "kb":
size = size * KB size *= KB
case "mb": case "mb":
size = size * MB size *= MB
case "gb": case "gb":
size = size * GB size *= GB
case "tb": case "tb":
size = size * TB size *= TB
} }
attachment, err := strconv.ParseBool(queryParams.Get("attachment")) attachment, err := strconv.ParseBool(queryParams.Get("attachment"))
@ -148,8 +151,12 @@ func whoamiHandler(w http.ResponseWriter, req *http.Request) {
} }
} }
if name != "" {
_, _ = fmt.Fprintln(w, "Name:", name)
}
hostname, _ := os.Hostname() hostname, _ := os.Hostname()
fmt.Fprintln(w, "Hostname:", hostname) _, _ = fmt.Fprintln(w, "Hostname:", hostname)
ifaces, _ := net.Interfaces() ifaces, _ := net.Interfaces()
for _, i := range ifaces { for _, i := range ifaces {
@ -163,10 +170,11 @@ func whoamiHandler(w http.ResponseWriter, req *http.Request) {
case *net.IPAddr: case *net.IPAddr:
ip = v.IP ip = v.IP
} }
fmt.Fprintln(w, "IP:", ip) _, _ = fmt.Fprintln(w, "IP:", ip)
} }
} }
_, _ = fmt.Fprintln(w, "RemoteAddr:", req.RemoteAddr)
if err := req.Write(w); err != nil { if err := req.Write(w); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
@ -204,10 +212,13 @@ func apiHandler(w http.ResponseWriter, req *http.Request) {
case *net.IPAddr: case *net.IPAddr:
ip = v.IP ip = v.IP
} }
if ip != nil {
data.IP = append(data.IP, ip.String()) data.IP = append(data.IP, ip.String())
} }
} }
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(data); err != nil { if err := json.NewEncoder(w).Encode(data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
@ -244,7 +255,7 @@ func healthHandler(w http.ResponseWriter, req *http.Request) {
func fillContent(length int64) io.ReadSeeker { func fillContent(length int64) io.ReadSeeker {
charset := "-ABCDEFGHIJKLMNOPQRSTUVWXYZ" charset := "-ABCDEFGHIJKLMNOPQRSTUVWXYZ"
b := make([]byte, length, length) b := make([]byte, length)
for i := range b { for i := range b {
b[i] = charset[i%len(charset)] b[i] = charset[i%len(charset)]

4
go.mod
View File

@ -1,3 +1,5 @@
module github.com/containous/whoami module github.com/containous/whoami
require github.com/gorilla/websocket v1.2.0 go 1.13
require github.com/gorilla/websocket v1.4.1

4
go.sum
View File

@ -1,2 +1,2 @@
github.com/gorilla/websocket v1.2.0 h1:VJtLvh6VQym50czpZzx07z/kw9EgAxI3x1ZB8taTMQQ= github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM=
github.com/gorilla/websocket v1.2.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=

24
tmpl.Dockerfile Normal file
View File

@ -0,0 +1,24 @@
FROM golang:1-alpine as builder
RUN apk --no-cache --no-progress add git ca-certificates tzdata make \
&& update-ca-certificates \
&& rm -rf /var/cache/apk/*
WORKDIR /go/whoami
# Download go modules
COPY go.mod .
COPY go.sum .
RUN GO111MODULE=on GOPROXY=https://proxy.golang.org go mod download
COPY . .
RUN GOARCH={{ .GoARCH }} GOARM={{ .GoARM }} make build
FROM scratch
COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /go/whoami/whoami .
ENTRYPOINT ["/whoami"]
EXPOSE 80