l2.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "encoding/json"
  6. "time"
  7. "bytes"
  8. "io"
  9. "strings"
  10. )
  11. type UserStruct struct{
  12. Age int `json:"age"`
  13. Name string `json:"name"`
  14. Email string `json:"email"`
  15. Alive bool `json:"alive"`
  16. }
  17. func polz() (int, string, string, bool) {
  18. fmt.Printf("Your age? ")
  19. var age int
  20. fmt.Scan(&age)
  21. fmt.Printf("Your name? ")
  22. var name string
  23. fmt.Scan(&name)
  24. fmt.Printf("Your email? ")
  25. var email string
  26. fmt.Scan(&email)
  27. fmt.Printf("Your alive?(y/n) ")
  28. var live string
  29. fmt.Scan(&live)
  30. LowerLive := strings.ToLower(live)
  31. var alive bool
  32. if LowerLive == "y" {
  33. alive = true
  34. } else if LowerLive == "n" {
  35. alive = false
  36. }
  37. return age, name, email, alive
  38. }
  39. func main() {
  40. age, name, email, alive := polz()
  41. user := UserStruct{
  42. Age: age,
  43. Name: name,
  44. Email: email,
  45. Alive: alive,
  46. }
  47. JsonData, err := json.Marshal(user)
  48. if err != nil {
  49. panic(err)
  50. }
  51. client := &http.Client{
  52. Timeout: 5 * time.Second,
  53. }
  54. req, err := http.NewRequest("POST", "http://127.0.0.1:7777/user", bytes.NewBuffer(JsonData))
  55. if err != nil {
  56. panic(err)
  57. }
  58. resp, err := client.Do(req)
  59. if err != nil {
  60. panic(err)
  61. }
  62. body, err := io.ReadAll(resp.Body)
  63. if err != nil {
  64. panic(err)
  65. }
  66. fmt.Printf("status code %d\n", resp.StatusCode)
  67. fmt.Println(string(body))
  68. }