server.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2021 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "bytes"
  17. "encoding/json"
  18. "fmt"
  19. "io/ioutil"
  20. "log"
  21. "math/rand"
  22. "net/http"
  23. "time"
  24. )
  25. func alert(w http.ResponseWriter, req *http.Request) {
  26. buf, bodyErr := ioutil.ReadAll(req.Body)
  27. if bodyErr != nil {
  28. log.Print("bodyErr ", bodyErr.Error())
  29. http.Error(w, bodyErr.Error(), http.StatusInternalServerError)
  30. return
  31. }
  32. rdr1 := ioutil.NopCloser(bytes.NewBuffer(buf))
  33. log.Printf("BODY: %q", rdr1)
  34. }
  35. var count = 0
  36. type Sensor struct {
  37. Temperature int `json: "temperature""`
  38. Humidity int `json: "humidiy"`
  39. }
  40. var s = &Sensor{}
  41. func pullSrv(w http.ResponseWriter, req *http.Request) {
  42. buf, bodyErr := ioutil.ReadAll(req.Body)
  43. if bodyErr != nil {
  44. log.Print("bodyErr ", bodyErr.Error())
  45. http.Error(w, bodyErr.Error(), http.StatusInternalServerError)
  46. return
  47. } else {
  48. fmt.Println(string(buf))
  49. }
  50. if count%2 == 0 {
  51. rand.Seed(time.Now().UnixNano())
  52. s.Temperature = rand.Intn(100)
  53. s.Humidity = rand.Intn(100)
  54. }
  55. fmt.Printf("%v\n", s)
  56. count++
  57. sd, err := json.Marshal(s)
  58. if err != nil {
  59. fmt.Println(err)
  60. return
  61. } else {
  62. if _, e := fmt.Fprintf(w, "%s", sd); e != nil {
  63. fmt.Println(e)
  64. }
  65. }
  66. }
  67. func main() {
  68. http.Handle("/", http.FileServer(http.Dir("web")))
  69. http.HandleFunc("/alert", alert)
  70. http.HandleFunc("/pull", pullSrv)
  71. http.ListenAndServe(":9090", nil)
  72. }