~ of Vetelko


Text version / Updated: May 30 01:10:24 2019


Golang web server in chroot in OpenBSD


Create file web-server.go containing simple Golang web server example:

package main

import (
    "fmt"
    "log"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello OpenBSD")
}

func main() {
    fmt.Printf("Starting server at localhost:8080")
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

To simplify the things we can create fully static go binary so we don’t need to copy runtime libraries into chroot:

$ env CGO_ENABLED=0 GOOS=openbsd GOARCH=amd64 \
  go build -a -o web-server

Copy web-server binary into /var/www/bin:

$ doas cp web-server /var/www/bin

Start server:

$ doas chroot -u www -g www /var/www /bin/web-server

Test it in the browser:

$ firefox http://localhost:8080

As a bonus you can try to run some benchmark and compare the result with any other technology. Here I’m using https://github.com/rakyll/hey

Summary:
  Total:        0.0312 secs
  Slowest:      0.0197 secs
  Fastest:      0.0002 secs
  Average:      0.0062 secs
  Requests/sec: 6415.9075
  Total data:   1000 bytes
  Size/request: 5 bytes

Response time histogram:
  0.000 [1]     |∎
  0.002 [42]    |∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎
  0.004 [63]    |∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎
  0.006 [22]    |∎∎∎∎∎∎∎∎∎∎∎∎∎∎
  0.008 [12]    |∎∎∎∎∎∎∎∎
  0.010 [14]    |∎∎∎∎∎∎∎∎∎
  0.012 [9]     |∎∎∎∎∎∎
  0.014 [16]    |∎∎∎∎∎∎∎∎∎∎
  0.016 [10]    |∎∎∎∎∎∎
  0.018 [8]     |∎∎∎∎∎
  0.020 [3]     |∎∎

Latency distribution:
  10% in 0.0012 secs
  25% in 0.0025 secs
  50% in 0.0040 secs
  75% in 0.0096 secs
  90% in 0.0143 secs
  95% in 0.0161 secs
  99% in 0.0194 secs

Details (average, fastest, slowest):
  DNS+dialup:    0.0013 secs, 0.0000 secs, 0.0088 secs
  DNS-lookup:    0.0001 secs, 0.0000 secs, 0.0038 secs
  req write:     0.0003 secs, 0.0000 secs, 0.0025 secs
  resp wait:     0.0032 secs, 0.0002 secs, 0.0088 secs
  resp read:     0.0001 secs, 0.0000 secs, 0.0021 secs

Status code distribution:
  [200] 200 responses