package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"time"

	chitin "code.justin.tv/rhys/nursery/xarth"
	"code.justin.tv/rhys/nursery/xarth/clog"
)

func init() {
	http.HandleFunc("/", handleHello)
	http.HandleFunc("/sleep", handleSleep)
	http.HandleFunc("/panic", handlePanic)
}

func main() {
	l, err := net.Listen("tcp", ":8080")
	if err != nil {
		log.Fatalf("bind=%q", err)
	}

	srv := &http.Server{
		ReadTimeout:  60 * time.Second,
		WriteTimeout: 60 * time.Second,
	}

	err = chitin.Serve(srv, l)
	if err != nil {
		log.Fatalf("serve=%q", err)
	}
}

func handleHello(w http.ResponseWriter, r *http.Request) {
	ctx, _ := chitin.Context(w, r)
	clog.Log(ctx).Printf("url=%q", r.URL)

	_, err := io.Copy(ioutil.Discard, r.Body)
	if err != nil {
		clog.Log(ctx).Printf("body-read-err=%q", err)
		return
	}

	fmt.Fprintf(w, "Hello, %q", r.URL)
}

func handleSleep(w http.ResponseWriter, r *http.Request) {
	time.Sleep(10 * time.Second)
}

func handlePanic(w http.ResponseWriter, r *http.Request) {
	panic("oops")
}
