1 package main 2 3 import ( 4 "database/sql" 5 "fmt" 6 "log" 7 "net/http" 8 "os" 9 "strconv" 10 11 _ "github.com/go-sql-driver/mysql" 12 ) 13 14 func maybeError ( err error ) { 15 if err != nil { 16 panic ( err . Error ()) 17 } 18 } 19 20 func getValuesFromRequest ( r * http . Request ) ( uint64 , float64 ) { 21 if r . FormValue ( "value" ) == "" || r . FormValue ( "timestamp" ) == "" { 22 panic ( "ERROR: value or timestamp empty" ) 23 } 24 25 value , err := strconv . ParseFloat ( r . FormValue ( "value" ), 64 ) 26 maybeError ( err ) 27 timestamp , err := strconv . ParseUint ( r . FormValue ( "timestamp" ), 10 , 64 ) 28 maybeError ( err ) 29 30 return timestamp , value 31 } 32 33 func executePreparedStatement ( preparedStatement string , timestamp uint64 , value float64 ) { 34 db , err := sql . Open ( "mysql" , "admin:pass@tcp(0.0.0.0:3306)/weather_station" ) 35 maybeError ( err ) 36 defer db . Close () 37 38 stmtIns , err := db . Prepare ( preparedStatement ) 39 maybeError ( err ) 40 defer stmtIns . Close () 41 42 _ , err = stmtIns . Exec ( timestamp , value ) 43 } 44 45 func insertIntoDb ( r * http . Request ) { 46 // the url path is smth like /temperature 47 // and maps directly to the table but without the leading / 48 table := r . URL . Path [ 1 : len ( r . URL . Path )] 49 timestamp , value := getValuesFromRequest ( r ) 50 executePreparedStatement ( "INSERT INTO`" + table + "` VALUES(FROM_UNIXTIME(?), ?)" , timestamp , value ) 51 } 52 53 func handler ( w http . ResponseWriter , r * http . Request ) { 54 if r . Method == "POST" { 55 insertIntoDb ( r ) 56 } else if r . Method == "GET" { 57 // GET FROM DATABASE 58 } else { 59 // HTTP METHOD NOT SUPPORTED 60 } 61 } 62 63 func getPort () string { 64 if os . Getenv ( "API_PORT" ) != "" { 65 return ":" + os . Getenv ( "API_PORT" ) 66 } else { 67 return ":8080" 68 } 69 } 70 71 func main () { 72 http . HandleFunc ( "/temperature" , handler ) 73 http . HandleFunc ( "/pressure" , handler ) 74 http . HandleFunc ( "/humidity" , handler ) 75 http . HandleFunc ( "/brightness" , handler ) 76 77 port := getPort () 78 79 fmt . Println ( "API listen on port" , port ) 80 log . Fatal ( http . ListenAndServe ( port , nil )) 81 }