package main

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

func longPolling(response http.ResponseWriter, request *http.Request) {

	response.Header().Set("Content-Type", "application/json")
	response.Header().Set("Access-Control-Allow-Origin", "*")
	response.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
	response.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding")
	response.WriteHeader(http.StatusOK)

	flusher, _ := response.(http.Flusher)
	for range 3 {
		data := []byte(fmt.Sprintf(`{"message": "Long Polling %s"}`, timeStamp()))
		response.Write(data)
		flusher.Flush()
		time.Sleep(1 * time.Second)
	}
	flusher.Flush()
}

func timeStamp() string {
	return time.Now().Format("2006-01-02 15:04:05")
}

func main() {
	log.Println("Starting server")
	log.Fatal(http.ListenAndServe(":8080", http.HandlerFunc(longPolling)))
}
