Skip to content

Instantly share code, notes, and snippets.

@mikattack
Last active October 16, 2015 12:57
Show Gist options
  • Save mikattack/5d0bb672d318bc14f0a4 to your computer and use it in GitHub Desktop.
Save mikattack/5d0bb672d318bc14f0a4 to your computer and use it in GitHub Desktop.
Basic chunked response server and client. There's a single, obvious error in here that poor error handling obscures. See if you can spot it.
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
type timestamp struct {
Time string `json:"time"`
}
func main() {
client := &http.Client{}
req, err := http.NewRequest("GET", "http://localhost:28002", nil)
if err != nil {
fmt.Printf("ERROR: %s\n", err.Error())
}
req.Header.Add("Accept", "application/json")
if res, err := client.Do(req); err != nil {
fmt.Printf("ERROR: %s\n", err.Error())
} else {
defer res.Body.Close()
decoder := json.NewDecoder(res.Body)
for {
var ts timestamp
err := decoder.Decode(&ts)
if err == io.EOF {
fmt.Printf("End of response.\n")
break
}
if err != nil {
fmt.Printf("ERROR: %s\n", err.Error())
break
}
fmt.Printf("Time: %s\n", ts.Time)
}
}
}
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"time"
)
var HTTP_ADDR string = "28002"
type timestamp struct {
Time time.Time `json:"time"`
}
func clockStreamHandler(res http.ResponseWriter, req *http.Request) {
clientGone := res.(http.CloseNotifier).CloseNotify()
encoder := json.NewEncoder(res)
res.Header().Set("Content-Type", "application/json")
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for {
ts := timestamp{ Time:time.Now() }
encoder.Encode(ts)
res.(http.Flusher).Flush()
select {
case <-ticker.C:
// Continue
case <-clientGone:
log.Printf("Client %v disconnected", req.RemoteAddr)
return
}
}
}
func main() {
log.SetOutput(os.Stdout)
log.SetFlags(log.LstdFlags | log.Lshortfile)
log.Printf("Listening on " + HTTP_ADDR)
http.HandleFunc("/clock", clockStreamHandler)
go func() {
log.Fatal(http.ListenAndServe(":" + HTTP_ADDR, nil))
}()
select {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment