|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "net/http" |
| 8 | + "os" |
| 9 | + |
| 10 | + "github.com/gorilla/mux" |
| 11 | + "github.com/joho/godotenv" |
| 12 | +) |
| 13 | + |
| 14 | +type Data struct { |
| 15 | + Pressure float64 `json:"pressure"` |
| 16 | + Temperature float64 `json:"maxtemp"` |
| 17 | +} |
| 18 | + |
| 19 | +var data Data |
| 20 | + |
| 21 | +func HealthHandler(w http.ResponseWriter, r *http.Request) { |
| 22 | + w.Header().Set("Content-Type", "application/json") |
| 23 | + w.WriteHeader(http.StatusOK) |
| 24 | + json.NewEncoder(w).Encode(map[string]string{"status": "ok"}) |
| 25 | +} |
| 26 | +func DataHandler(w http.ResponseWriter, r *http.Request) { |
| 27 | + w.Header().Set("Content-Type", "application/json") |
| 28 | + if r.Method == "GET" { |
| 29 | + json.NewEncoder(w).Encode(data) |
| 30 | + } else if r.Method == "POST" { |
| 31 | + var newData Data |
| 32 | + err := json.NewDecoder(r.Body).Decode(&newData) |
| 33 | + data.Pressure = newData.Pressure |
| 34 | + data.Temperature = newData.Temperature |
| 35 | + if err != nil { |
| 36 | + http.Error(w, err.Error(), http.StatusBadRequest) |
| 37 | + return |
| 38 | + } |
| 39 | + w.WriteHeader(http.StatusOK) |
| 40 | + json.NewEncoder(w).Encode(data) |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +func main() { |
| 45 | + err := godotenv.Load() |
| 46 | + if err != nil { |
| 47 | + log.Fatal("Error loading .env file") |
| 48 | + } |
| 49 | + |
| 50 | + r := mux.NewRouter() |
| 51 | + r.HandleFunc("/health", HealthHandler).Methods("GET") |
| 52 | + r.HandleFunc("/data", DataHandler).Methods("GET", "POST") |
| 53 | + |
| 54 | + port := os.Getenv("PORT") |
| 55 | + if port == "" { |
| 56 | + port = "8000" |
| 57 | + } |
| 58 | + fmt.Printf("Starting server at port %s\n", port) |
| 59 | + log.Fatal(http.ListenAndServe(":"+port, r)) |
| 60 | +} |
0 commit comments