package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
tle "git.darknebu.la/Satellite/tle"
"github.com/gorilla/mux"
)
// indexHandler displays an index page
func indexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s", "
Hello World
")
}
// dumpallHandler dumps all categories
func dumpallHandler(w http.ResponseWriter, r *http.Request) {
log.Println("[ ] Dumping all TLEs")
// read the name of the categories from the categories.txt file and write
// the result to the categories slice
content, err := ioutil.ReadFile("categories.txt")
if err != nil {
log.Printf("%s\n", "could not read categories.txt file!")
}
lines := strings.Split(string(content), "\n")
for _, line := range lines {
if line != "" {
categories = append(categories, line)
}
}
// download all the categories to the data/ directory
for _, category := range categories {
fmt.Fprintf(w, "downloading %s... ", category)
log.Printf("downloading %s... ", category)
downloadCategory(category)
fmt.Fprintf(w, "done.\n")
}
log.Println("[+] Done dumping all TLEs")
}
// get Handler returns the specified TLE
func getHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
// read the TLEs from the categories file
// TODO: Handle caching
// - dump all if not present
// - if old, fetch from celestrack
//content, err := ioutil.ReadFile("categories.txt")
//if err != nil {
// log.Println("Could note read categories.txt")
//}
// open the file containing the data for the individual station
categoryPath := fmt.Sprintf("data/%s.txt", vars["station"])
content, err := ioutil.ReadFile(categoryPath)
if err != nil {
log.Printf("Could not open %s", categoryPath)
}
lines := strings.Split(string(content), "\n")
// iterate over all lines searching for the satellite
var j int
for i, line := range lines {
if strings.Contains(line, vars["name"]) {
j = i
break
}
}
RawTLE := strings.Join(lines[j:j+3], "\n")
/*
RawTLE := `ISS (ZARYA)
1 25544U 98067A 19229.39083552 .00000228 00000-0 11917-4 0 9993
2 25544 51.6447 57.6210 0007373 294.0868 138.8050 15.50381554184754`
*/
// handle the response according to the query parameter "format"
// if ?format=json is given, return
if r.URL.Query().Get("format") == "json" {
w.Header().Set("Content-Type", "application/json")
JSONTLE, err := tle.NewTLE(RawTLE)
if err != nil {
fmt.Println(err)
}
// convert the TLE to json
b, err := json.MarshalIndent(JSONTLE, "", " ")
if err != nil {
fmt.Println("error: ", err)
}
fmt.Fprintf(w, string(b))
//fmt.Fprintf(w, "{\"response\": \"Getting the TLE for %s/%s as json\"}", vars["station"], vars["name"])
} else {
fmt.Fprintf(w, "Getting the TLE for %s/%s raw", vars["station"], vars["name"])
}
}