server.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2021-2023 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"
  20. "log"
  21. "math/rand"
  22. "net/http"
  23. )
  24. func alert(w http.ResponseWriter, req *http.Request) {
  25. buf, bodyErr := io.ReadAll(req.Body)
  26. if bodyErr != nil {
  27. log.Print("bodyErr ", bodyErr.Error())
  28. http.Error(w, bodyErr.Error(), http.StatusInternalServerError)
  29. return
  30. }
  31. rdr1 := io.NopCloser(bytes.NewBuffer(buf))
  32. log.Printf("BODY: %q", rdr1)
  33. }
  34. var count = 0
  35. type Sensor struct {
  36. Temperature int `json:"temperature"`
  37. Humidity int `json:"humidity"`
  38. }
  39. var s = &Sensor{}
  40. func pullSrv(w http.ResponseWriter, req *http.Request) {
  41. buf, bodyErr := io.ReadAll(req.Body)
  42. if bodyErr != nil {
  43. log.Print("bodyErr ", bodyErr.Error())
  44. http.Error(w, bodyErr.Error(), http.StatusInternalServerError)
  45. return
  46. } else {
  47. fmt.Println(string(buf))
  48. }
  49. if count%2 == 0 {
  50. s.Temperature = rand.Intn(100)
  51. s.Humidity = rand.Intn(100)
  52. }
  53. fmt.Printf("%v\n", s)
  54. count++
  55. sd, err := json.Marshal(s)
  56. if err != nil {
  57. fmt.Println(err)
  58. return
  59. } else {
  60. if _, e := fmt.Fprintf(w, "%s", sd); e != nil {
  61. fmt.Println(e)
  62. }
  63. }
  64. }
  65. func main() {
  66. http.Handle("/", http.FileServer(http.Dir("web")))
  67. http.HandleFunc("/alert", alert)
  68. http.HandleFunc("/pull", pullSrv)
  69. http.ListenAndServe(":9090", nil)
  70. }