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", "
TLE2JSON api
")
fmt.Fprintf(w, "%s", "Usage: Make a get request to /{station}/{name}")
}
// dumpallHandler dumps all categories
func dumpallHandler(w http.ResponseWriter, r *http.Request) {
log.Println("[ ] Dumping all TLEs")
dumpall()
log.Println("[+] Done dumping all TLEs")
}
// get Handler returns the specified TLE
func getHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
// define where the file containing the spoecified categories lies
categoryPath := fmt.Sprintf("data/%s.txt", vars["station"])
// this will only download the category if the file does not exist or if it
// is to old
downloadCategory(vars["station"])
// open the file containing the data for the individual 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")
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))
}