• HTTP请求


    1. get请求

     1 package main
     2 
     3 import (
     4     "fmt"
     5     "io/ioutil"
     6     "net/http"
     7     "os"
     8 )
     9 
    10 func main() {
    11 
    12     resp, err := http.Get("https://baike.baidu.com/item/书/130176?fr=aladdin")
    13     HandleError(err, "http.Get")
    14 
    15     defer resp.Body.Close()
    16 
    17     bytes, e := ioutil.ReadAll(resp.Body)
    18     HandleError(e, "outil.ReadAll")
    19 
    20     fmt.Println("get:", string(bytes))
    21 
    22 }
    23 
    24 func HandleError(err error, when string) {
    25     if err != nil {
    26         fmt.Println(err, "net.Listen")
    27         os.Exit(1)
    28 
    29     }
    30 }

    2. post请求

     1 package main
     2 
     3 import (
     4     "fmt"
     5     "io/ioutil"
     6     "net/http"
     7     "os"
     8     "strings"
     9 )
    10 
    11 func main() {
    12 
    13     url := "https://httpbin.org/post?name=love"
    14     //携带的数据类型,表单
    15     resp, err := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader("rmb=0.5&hobby=love"))
    16     HandleError(err, "htp.post")
    17     defer resp.Body.Close()
    18 
    19     bytes, e := ioutil.ReadAll(resp.Body)
    20     HandleError(e, "ioutil.ReadAll")
    21     fmt.Println(string(bytes))
    22 
    23 }
    24 
    25 func HandleError(err error, when string) {
    26     if err != nil {
    27         fmt.Println(err, "net.Listen")
    28         os.Exit(1)
    29 
    30     }
    31 }

    3. 搭建http服务端

     1 package main
     2 
     3 import (
     4     "net/http"
     5     "strconv"
     6 )
     7 
     8 func main() {
     9 
    10     //路由规则1
    11     http.HandleFunc("/shit", func(writer http.ResponseWriter, request *http.Request) {
    12         writer.Write([]byte("im ok!"))
    13     })
    14 
    15     //路由规则2
    16     http.HandleFunc("/hello", func(writer http.ResponseWriter, request *http.Request) {
    17         writer.Write([]byte("请求的方法=" + request.Method))
    18         writer.Write([]byte("请求的内容长度=" + strconv.Itoa(int(request.ContentLength))))
    19         writer.Write([]byte("请求的主机=" + request.Host))
    20         writer.Write([]byte("请求的协议=" + request.Proto))
    21         writer.Write([]byte("请求的远程地址=" + request.RemoteAddr))
    22         writer.Write([]byte("请求的路由=" + request.RequestURI))
    23         writer.Write([]byte("朕已收到信息"))
    24 
    25     })
    26 
    27     //监听
    28     http.ListenAndServe("0.0.0.0:8080", nil)
    29 }

    end

  • 相关阅读:
    实时监听输入框值变化的完美方案:oninput & onpropertychange
    展示两行,超出用。。。表示
    修改下拉框滚动条样式
    js单线程工作
    锚点
    火狐图片乱码
    解决重复提交的几种方法
    forward和redirect的区别
    form表单刷新自动提交
    addEventListener和attachEvent的区别
  • 原文地址:https://www.cnblogs.com/chaoyangxu/p/12191623.html
Copyright © 2020-2023  润新知