package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" "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) // read the TLEs from the categories file // TODO: Handle caching // - dump all if not present // - if old, fetch from celestrack // define where the file containing the spoecified categories lies categoryPath := fmt.Sprintf("data/%s.txt", vars["station"]) // find out if the file exists or not if _, err := os.Stat(categoryPath); os.IsNotExist(err) { // if it does not exist, download the category 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)) }