go语言之http

go语言http

1、net/http 包提供的 http.ListenAndServe() 方法,在指定的地址监听
该方法用于在指定的 TCP 网络地址 addr 进行监听,然后调用服务端处理程序来处理传入的连 接请求。该方法有两个参数:第一个参数 addr 即监听地址;第二个参数表示服务端处理程序, 通常为空,这意味着服务端调用 http.DefaultServeMux 进行处理,而服务端编写的业务逻 辑处理程序 http.Handle() 或 http.HandleFunc() 默认注入 http.DefaultServeMux 中。
2.处理https请求
func ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) error
3.路由
http.HandleFunc()方法接受两个参数
第一个参数是HTTP请求的 目标路径"/hello",该参数值可以是字符串,也可以是字符串形式的正则表达式
第二个参数指定具体的回调方法,比如helloHandler。
当我们的程序运行起来后,访问http://localhost:8080/hello , 程序就会去调用helloHandler()方法中的业务逻辑程序。


4.get/post访问

resp, err := http.Get("...")
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
resp, err:=http.Post(“.....”, ”application/x-www-form-urlencoded”, strings.NewReader(“..=...”))

defer resp.Body.Close()

body,err:=ioutil.ReadAll(resp.Body)

fmt.Println(string(body))

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
)

func main() {
    //模拟一个post提交请求
    resp, err := http.Post("http://www.baidu.com", "application/x-www-form-urlencoded", strings.NewReader("id=1"))
    if err != nil {
        panic(err)
    }
    //关闭连接
    defer resp.Body.Close()
    //读取报文中所有内容
    body, err := ioutil.ReadAll(resp.Body)
    //输出内容
    fmt.Println(string(body))
}

模拟一个http server 监听地址:127.0.0.1:8080

// http_server.go
package main

import (
    //"fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("hello world!"))
    })

    http.ListenAndServe("127.0.0.1:8080", nil)
}

go语言之http

转载于:https://blog.51cto.com/huwho/2316694

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值