route/cmd/construct/builtin.go

70 lines
1.3 KiB
Go

package main
import (
"context"
"flag"
"fmt"
"log"
"net/http"
"os"
"runtime"
"github.com/kr/pretty"
"go.uber.org/atomic"
)
var (
hits *atomic.Int64
)
func init() {
hits = atomic.NewInt64(0)
}
func demoServerHandler(msg string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Route is go!")
fmt.Fprintf(w, "%s\n", pretty.Sprintf("%s", r.Header))
hn, _ := os.Hostname()
fmt.Fprintf(w, "message: %s\n", msg)
fmt.Fprintf(w, "Served by %s running %s\n", hn, runtime.GOOS)
fmt.Fprintf(w, "Hit count: %d", hits.Inc())
ip := r.Header.Get("X-Remote-Ip")
if ip != "" {
log.Printf("Hit from %s: %s", ip, r.RequestURI)
}
})
}
func demoServer(ctx context.Context, args []string) error {
fs := flag.NewFlagSet("server", flag.ContinueOnError)
addr := fs.String("addr", ":9090", "http address to listen on")
msg := fs.String("msg", "now here's a little lesson in trickery...", "custom message to add to each page render")
err := fs.Parse(args)
if err != nil {
return err
}
hs := &http.Server{
Addr: *addr,
Handler: demoServerHandler(*msg),
}
go hs.ListenAndServe()
log.Printf("listening on %s", *addr)
for {
select {
case <-ctx.Done():
sctx := context.Background()
hs.Shutdown(sctx)
return nil
}
}
}