Created
June 15, 2020 11:04
-
-
Save infoverload/9ac107b89cf4e4044432f6a433780eef to your computer and use it in GitHub Desktop.
Accompanies the Generate Time Series in Go tutorial for CrateDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"time" | |
"github.com/jackc/pgx/v4" | |
) | |
var conn *pgx.Conn | |
type issInfo struct { | |
IssPosition struct { | |
Longitude string `json:"longitude"` | |
Latitude string `json:"latitude"` | |
} `json:"iss_position"` | |
} | |
func insertData(position string) error { | |
_, err := conn.Exec(context.Background(), "INSERT INTO iss (position) VALUES ($1)", position) | |
return err | |
} | |
func getISSPosition() (string, error) { | |
var i issInfo | |
response, err := http.Get("http://api.open-notify.org/iss-now.json") | |
if err != nil { | |
return "", fmt.Errorf("unable to retrieve request: %v", err) | |
} | |
defer response.Body.Close() | |
if response.StatusCode/100 != 2 { | |
return "", fmt.Errorf("bad response status: %s", response.Status) | |
} | |
responseData, err := ioutil.ReadAll(response.Body) | |
if err != nil { | |
return "", fmt.Errorf("unable to read response body: %v", err) | |
} | |
err = json.Unmarshal(responseData, &i) | |
if err != nil { | |
return "", fmt.Errorf("unable to unmarshal response body: %v", err) | |
} | |
s := fmt.Sprintf("(%s, %s)", i.IssPosition.Longitude, i.IssPosition.Latitude) | |
return s, nil | |
} | |
func main() { | |
var err error | |
conn, err = pgx.Connect(context.Background(), "postgresql://crate@localhost:5432/doc") | |
if err != nil { | |
log.Fatalf("unable to connect to database: %v\n", err) | |
} | |
defer conn.Close(context.Background()) | |
conn.Exec(context.Background(), "CREATE TABLE [ IF NOT EXISTS ] iss ( | |
timestamp TIMESTAMP GENERATED ALWAYS AS CURRENT_TIMESTAMP, | |
position GEO_POINT)") | |
for { | |
pos, err := getISSPosition() | |
if err != nil { | |
log.Fatalf("unable to get ISS position: %v\n", err) | |
} else { | |
err = insertData(pos) | |
if err != nil { | |
log.Fatalf("unable to insert data: %v\n", err) | |
} | |
} | |
fmt.Println("Sleeping for 5 seconds...") | |
time.Tick(time.Second * 5) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment