I have written a basic server which is getting a mock sensor data from an api, and pass it to the client application which i am intending to builld.
here is the server code
package main
import (
"fmt"
"log"
"net/http"
"time"
"io/ioutil"
"encoding/json"
)
type MyData []struct {
TimeStamp int64 `json:"timeStamp"`
Y0 string `json:"y0"`
Y1 string `json:"y1"`
Y2 string `json:"y2"`
Y3 string `json:"y3"`
}
func main(){
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}
func handler(w http.ResponseWriter,r *http.Request){
log.Println("handler Started ")
defer log.Println("handler Ended")
ctx := r.Context()
data_chan := make(chan interface{})
defer close(data_chan)
defer fmt.Println("ok")
cha := getLiveDataStream(data_chan)
for {
select {
case v := <-cha:
fmt.Printf("Hello i am hit by: %v \n", v)
fmt.Fprintln(w, v)
case <-time.After(time.Second * 10 ):
fmt.Println("overslept ")
case <- ctx.Done():
err := ctx.Err()
log.Print(err)
http.Error(w, err.Error(),http.StatusInternalServerError)
return
}
}
}
func getLiveDataStream(data_chan chan interface{}) chan interface {} {
url := "https://raw.githubusercontent.com/shahidammer/timeseries_data/master/data.json"
res, err := http.Get(url)
defer res.Body.Close()
if err != nil {log.Fatal(err)}
if res.StatusCode != http.StatusOK {log.Fatal(res.Status)}
body, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {log.Fatal(readErr)}
data := MyData{}
err = json.Unmarshal([]byte(body), &data)
if err != nil {fmt.Println(err);return nil}
go func(){
for _, v := range data {
time.Sleep(time.Second)
data_chan <- v
}
}()
return data_chan
}
When i curl it with curl localhost:8080, I am not getting anything printed out, but when i remove the time.sleep, i can see the output.
I want to write a client script which will listen to the server, and print the data as he gets it.
Sorry for the naive question, I have just started Go.