当前位置:   article > 正文

golang最简单的server和client_newalgoservingclient

newalgoservingclient

client端

  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "net/url"
  8. )
  9. func main() {
  10. request_url := "http://localhost:8080/"
  11. // 要 POST的 参数
  12. form := url.Values{
  13. "name": {"xiaoming"},
  14. "address": {"beijing"},
  15. "subject": {"Hello"},
  16. "from": {"china"},
  17. }
  18. // func Post(url string, bodyType string, body io.Reader) (resp *Response, err error) {
  19. //对form进行编码
  20. body := bytes.NewBufferString(form.Encode())
  21. rsp, err := http.Post(request_url, "application/x-www-form-urlencoded", body)
  22. if err != nil {
  23. panic(err)
  24. }
  25. defer rsp.Body.Close()
  26. body_byte, err := ioutil.ReadAll(rsp.Body)
  27. if err != nil {
  28. panic(err)
  29. }
  30. fmt.Println(string(body_byte))
  31. }

 

server端

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "net/http"
  6. )
  7. func main() {
  8. http.HandleFunc("/", ExampleHandler)
  9. if err := http.ListenAndServe(":8080", nil); err != nil {
  10. log.Fatal(err)
  11. }
  12. }
  13. func ExampleHandler(w http.ResponseWriter, r *http.Request) {
  14. // Double check it's a post request being made
  15. if r.Method != http.MethodPost {
  16. w.WriteHeader(http.StatusMethodNotAllowed)
  17. fmt.Fprintf(w, "invalid_http_method")
  18. return
  19. }
  20. // Must call ParseForm() before working with data
  21. r.ParseForm()
  22. // Log all data. Form is a map[]
  23. log.Println(r.Form)
  24. // Print the data back. We can use Form.Get() or Form["name"][0]
  25. fmt.Fprintf(w, "Hello "+r.Form.Get("name"))
  26. }
  27. //可以直接命令行请求
  28. //curl -X POST http://localhost:8080 -d "name=zhangsan"

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/962596
推荐阅读
相关标签
  

闽ICP备14008679号