Wrote an Webserver to spit out a random planet with a go backend and an astro front end
This commit is contained in:
87
test2.go
Normal file
87
test2.go
Normal file
@@ -0,0 +1,87 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// Fetch data from NASA Exoplanet API
|
||||
func fetchExoplanetData(query string) ([]map[string]interface{}, error) {
|
||||
baseURL := "https://exoplanetarchive.ipac.caltech.edu/TAP/sync"
|
||||
|
||||
params := url.Values{}
|
||||
params.Set("query", query)
|
||||
params.Set("format", "json")
|
||||
|
||||
fullURL := baseURL + "?" + params.Encode()
|
||||
resp, err := http.Get(fullURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetch error: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read error: %v", err)
|
||||
}
|
||||
|
||||
var results []map[string]interface{}
|
||||
if err := json.Unmarshal(body, &results); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal error: %v", err)
|
||||
}
|
||||
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// Handler: /planets
|
||||
func planetsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
year := r.URL.Query().Get("year")
|
||||
query := "SELECT pl_name, disc_year FROM pscomppars"
|
||||
if year != "" {
|
||||
query += fmt.Sprintf(" WHERE disc_year = %s", year)
|
||||
}
|
||||
|
||||
results, err := fetchExoplanetData(query)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// Add inside each handler, before writing the response:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
writeJSON(w, results)
|
||||
}
|
||||
|
||||
// Handler: /planets/large-radius
|
||||
func largeRadiusHandler(w http.ResponseWriter, r *http.Request) {
|
||||
query := "SELECT pl_name, pl_radj FROM pscomppars WHERE pl_radj > 5"
|
||||
|
||||
results, err := fetchExoplanetData(query)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// Add inside each handler, before writing the response:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
writeJSON(w, results)
|
||||
}
|
||||
|
||||
// Helper to write JSON response
|
||||
func writeJSON(w http.ResponseWriter, data interface{}) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
|
||||
// Main
|
||||
func main() {
|
||||
http.HandleFunc("/planets", planetsHandler)
|
||||
http.HandleFunc("/planets/large-radius", largeRadiusHandler)
|
||||
|
||||
fmt.Println("Server running at http://localhost:8080")
|
||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||
}
|
||||
Reference in New Issue
Block a user