June 11, 2014

golang http client Server Sent Event receiver

package main

import (
 "crypto/tls"
 "log"
 "bufio"
 "net/http"
 "time"
)

func main() {
 var client *http.Client
 tr := &http.Transport{
  TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
 }

 client = &http.Client{tr, nil, nil, 0 * time.Second}

 /* open a request, can't use httpclient.Get because we need the http.Request so we can close the connection later */
 req, err := http.NewRequest("GET", "https://dev1.advistatech.com/sse2.php", nil)
 if err != nil {
  log.Fatal(err);
 }

 resp, err := client.Do(req)
 if err != nil {
  log.Fatal(err);
 }
 log.Printf("connected\n");

 reader:=bufio.NewReader(resp.Body);
 for {
  line,err:=reader.ReadString('\n');
  if err != nil {
   log.Fatal(err);
  }else{
   log.Printf("resp:%s\n",line);
  }
 }

 //respbytes, _ := ioutil.ReadAll(resp.Body)
 //log.Printf("resp: %s\n", respbytes)

 resp.Body.Close()
}

No comments:

Post a Comment