l1.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "encoding/json"
  6. "strings"
  7. )
  8. type User struct{
  9. Age int `json:"age"`
  10. Name string `json:"name"`
  11. Email string `json:"email"`
  12. Alive bool `json:"alive"`
  13. }
  14. var setChan = make(chan User)
  15. func handle(w http.ResponseWriter, r *http.Request) {
  16. if r.Method != http.MethodPost {
  17. http.Error(w, "not", http.StatusMethodNotAllowed)
  18. return
  19. }
  20. var data User
  21. err := json.NewDecoder(r.Body).Decode(&data)
  22. if err != nil {
  23. http.Error(w,"no", http.StatusBadRequest)
  24. return
  25. }
  26. defer r.Body.Close()
  27. i := 0
  28. if data.Age > 150 {
  29. i++
  30. }
  31. CheckEmail := strings.ContainsAny(data.Email, "@.")
  32. if CheckEmail != true {
  33. i++
  34. }
  35. if data.Alive != true {
  36. i++
  37. }
  38. if i != 0 {
  39. msg := fmt.Sprintf("Error: %d", i)
  40. http.Error(w, msg, http.StatusBadRequest)
  41. return
  42. }
  43. setChan <- data
  44. w.WriteHeader(http.StatusOK)
  45. w.Write([]byte("Data received"))
  46. }
  47. func WatchChanell() {
  48. for u := range setChan {
  49. JsonData, err := json.Marshal(u)
  50. if err != nil { continue }
  51. fmt.Println(string(JsonData))
  52. }
  53. }
  54. func main() {
  55. go WatchChanell()
  56. http.HandleFunc("/user", handle)
  57. fmt.Println(":7777")
  58. err := http.ListenAndServe(":7777", nil)
  59. if err != nil {
  60. panic(err)
  61. }
  62. }