Problem in creating a simple web service in Go

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.

I don’t understand why do you use the go routine and channels for that. I guess simple unmarshal and print to output will be enough.

1 Like

I am trying to depict a mock sensor server, where you recieve data after 1 sec interval.

Something like this? :wink:

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

type Sensor struct {
	TimeStamp int64  `json:"timeStamp"`
	Y0        string `json:"y0"`
	Y1        string `json:"y1"`
	Y2        string `json:"y2"`
	Y3        string `json:"y3"`
}

var Sensors []Sensor

func main() {
	// curl -X GET 'http://localhost:8080'
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		res, _ := http.Get("https://raw.githubusercontent.com/shahidammer/timeseries_data/master/data.json")
		body, _ := ioutil.ReadAll(res.Body)
		json.Unmarshal(body, &Sensors)
		//fmt.Printf("%v", Sensors)
		time.Sleep(time.Second)
		for _, r := range Sensors {
			fmt.Println(r.TimeStamp, r.Y0, r.Y1, r.Y2, r.Y3)
		}
	})
	http.ListenAndServe(":8080", nil)
}

Thanks geosoft1 but i am not looking for something like this, I want something which is continously sending messages (data) after every one second interval. At the moment my server is sending it, all i need is a client app which can get the data at one second interval, i hope you get me now

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.