http请求

http请求 #

go内置net/http包作为网络请求包,提供了HTTP客户端和服务端的实现
文档: https://pkg.go.dev/net/http?tab=doc

文档: https://pkg.go.dev/net/http?tab=doc

net/http包常用函数 #

content-type:application/x-www-form-urlencoded
            application/json
发起get请求
func Get(url string) (resp *Response结构体, err error)

发起post请求
func Post(url, contentType string, body io.Reader接口) (resp *Response结构体, err error)
    url.Values类型为type Values map[string][]string,且该类型有自己的方法
func PostForm(url string, data url.Values) (resp *Response, err error)

发起head请求
func Head(url string) (resp *Response, err error)

jsonData, err := json.Marshal(结构体|map类型等) 返回[]byte, error
body = bytes.NewReader(jsonData) byte切片转*Reader结构体指针
body = strings.NewReader(字符串) 字符串转*Reader结构体指针

创建一个http请求结构体对象,一般与http.Client结构体的Do方法配合使用
func NewRequest(method, url string, body io.Reader) (*Request结构体, error)
示例:
    req, err := http.NewRequest("GET", "http://www.xxx.com", strings.NewReader("a=1&b=2"));
    client := &http.Client{} //结构体指针
    resp, err := client.Do(req)

入参FileSystem接口变量(目录),返回Handler接口
func FileServer(root FileSystem) Handler
设置路由,第2个参数接收只要实现了Handler接口变量均可
func Handle(pattern string路由, handler Handler接口变量)
设置路由,第2个参数为函数
func HandleFunc(pattern string路由, handler func(ResponseWriter接口, *Request结构体))
监听ip和端口,addr="ip:端口",其中ip可以省略
func ListenAndServe(addr string, handler Handler) error

net/http包下的常用类型 #

//把字符串转为http.Dir类型,type Dir string,该类型实现了本包的FileSystem接口
dir:=http.Dir("./views")

net/http包下的接口 #

type FileSystem interface {
	Open(name string) (File, error)
}

type Handler interface {
	ServeHTTP(ResponseWriter接口, *Request结构体)
}


net/url包下的常用类型 #

type Values map[string][]string 类型支持的方法如下:
    func (v Values) Set(key, value string) 设置与覆盖
    func (v Values) Add(key, value string) 追加
    func (v Values) Get(key string) string 获取
    func (v Values) Del(key string) 删除
    func (v Values) Encode() string 转成url参数值,如:bar=baz&foo=quux

示例:
urlParamData := url.Values{}
urlParamData.Set("userid", "123")
urlParamData.Set("nickname", "你好'!")
println(urlParamData.Get("userid"))
println(urlParamData.Encode())

示例2:
c2 := url.Values{"nickname": {"中国","上海"}, "userid": {"123"}}
println(c2.Encode())

net/http包下的常用结构体 #

http.Client结构体支持的方法如下:
    func (c *Client) Do(req *Request) (*Response, error)
    func (c *Client) Get(url string) (resp *Response, err error)
    func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error)
    func (c *Client) Head(url string) (resp *Response, err error)
    func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)


go创建静态服务示例 #

package main

import (
	"net/http"
	"os"
	"path/filepath"
)

func main() {
	basePath, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		basePath = "."
	}
	//1. 设置目录
	//把字符串转为http.Dir类型,type Dir string并实现了FileSystem接口
	dir:=http.Dir(basePath + "/views")
	println("监听的静态文件目录:", dir)
	//2. 设置文件静态文件服务目录
	//func FileServer(root FileSystem) Handler
	handler01 := http.FileServer(dir)
	//3. 设置路由
	//func Handle(pattern string路由, handler Handler接口变量)
	http.Handle("/", handler01)
	//1,2,3步写成一行写法:http.Handle("/", http.FileServer(http.Dir(basePath + "/views")))
	//4. 启动服务并监听8081端口
	//func ListenAndServe(addr string, handler Handler) error
	http.ListenAndServe(":8081", nil)

}
Build by Loppo 0.6.15