GOLAND HTTP请求 POST GET

180it 2021-10-03 AM 1489℃ 0条
  1. get请求

    package main

    import (

     "fmt"
     "io/ioutil"
     "net/http"
     "os"

    )

    func main() {

     resp, err := http.Get("https://baike.baidu.com/item/书/130176?fr=aladdin")
     HandleError(err, "http.Get")
    
     defer resp.Body.Close()
    
     bytes, e := ioutil.ReadAll(resp.Body)
     HandleError(e, "outil.ReadAll")
    
     fmt.Println("get:", string(bytes))
    

    }

    func HandleError(err error, when string) {

     if err != nil {
         fmt.Println(err, "net.Listen")
         os.Exit(1)
    
     }

    }

  2. post请求

    package main

    import (

     "fmt"
     "io/ioutil"
     "net/http"
     "os"
     "strings"

    )

    func main() {

     url := "https://httpbin.org/post?name=love"
     //携带的数据类型,表单
     resp, err := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader("rmb=0.5&hobby=love"))
     HandleError(err, "htp.post")
     defer resp.Body.Close()
    
     bytes, e := ioutil.ReadAll(resp.Body)
     HandleError(e, "ioutil.ReadAll")
     fmt.Println(string(bytes))
    

    }

    func HandleError(err error, when string) {

     if err != nil {
         fmt.Println(err, "net.Listen")
         os.Exit(1)
    
     }

    }

  3. 搭建http服务端

    package main

    import (

     "net/http"
     "strconv"

    )

    func main() {

     //路由规则1
     http.HandleFunc("/shit", func(writer http.ResponseWriter, request *http.Request) {
         writer.Write([]byte("im ok!"))
     })
    
     //路由规则2
     http.HandleFunc("/hello", func(writer http.ResponseWriter, request *http.Request) {
         writer.Write([]byte("请求的方法=" + request.Method))
         writer.Write([]byte("请求的内容长度=" + strconv.Itoa(int(request.ContentLength))))
         writer.Write([]byte("请求的主机=" + request.Host))
         writer.Write([]byte("请求的协议=" + request.Proto))
         writer.Write([]byte("请求的远程地址=" + request.RemoteAddr))
         writer.Write([]byte("请求的路由=" + request.RequestURI))
         writer.Write([]byte("朕已收到信息"))
    
     })
    
     //监听
     http.ListenAndServe("0.0.0.0:8080", nil)

    }

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

GOLAND HTTP请求 POST GET