l1.go 904 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "encoding/json"
  6. )
  7. type User struct{
  8. Age int `json:"age"`
  9. Name string `json:"name"`
  10. Email string `json:"email"`
  11. }
  12. var setChan = make(chan User)
  13. func handle(w http.ResponseWriter, r *http.Request) {
  14. if r.Method != http.MethodPost {
  15. http.Error(w, "not", http.StatusMethodNotAllowed)
  16. return
  17. }
  18. var data User
  19. err := json.NewDecoder(r.Body).Decode(&data)
  20. if err != nil {
  21. http.Error(w,"no", http.StatusBadRequest)
  22. return
  23. }
  24. defer r.Body.Close()
  25. setChan <- data
  26. w.WriteHeader(http.StatusOK)
  27. w.Write([]byte("Data received"))
  28. }
  29. func WatchChanell() {
  30. for u := range setChan {
  31. JsonData, err := json.Marshal(u)
  32. if err != nil { continue }
  33. fmt.Println(string(JsonData))
  34. }
  35. }
  36. func main() {
  37. go WatchChanell()
  38. http.HandleFunc("/user", handle)
  39. fmt.Println(":7777")
  40. err := http.ListenAndServe(":7777", nil)
  41. if err != nil {
  42. panic(err)
  43. }
  44. }