Skip to content

Commit d2415a8

Browse files
Add files via upload
1 parent 881ec40 commit d2415a8

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

goserverforsensor/go.mod

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
module github.com/adix/sensorserver
2+
3+
go 1.23.6
4+
5+
require github.com/gorilla/mux v1.8.1
6+
7+
require github.com/joho/godotenv v1.5.1

goserverforsensor/go.sum

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
2+
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
3+
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
4+
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=

goserverforsensor/main.go

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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

Comments
 (0)