go的net/http包使用

时间:2022-05-06
本文章向大家介绍go的net/http包使用,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
网上资料有点杂,有的还掺杂中间件进去,导致使用有障碍,所以,直接上官方文档:

1,首先搞清[]byte string的相互转换,最简单的方式就是

string转[]byte:[]byte(para string)

[]byte转string:string([]byte)

然后还有就是io包的一些实现方式,比如:

  1. bytes.NewBuffer(para []byte).String()

2,如何从request中获取form,body,head,下面是官方的api:

type Request

func NewRequest(method, urlStr string, body io.Reader) (*Request, error)

func ReadRequest(b *bufio.Reader) (req *Request, err error)

func (r *Request) ProtoAtLeast(major, minor int) bool

func (r *Request) UserAgent() string

func (r *Request) Referer() string

func (r *Request) AddCookie(c *Cookie)

func (r *Request) SetBasicAuth(username, password string)

func (r *Request) Write(w io.Writer) error

func (r *Request) WriteProxy(w io.Writer) error

func (r *Request) Cookies() []*Cookie

func (r *Request) Cookie(name string) (*Cookie, error)

func (r *Request) ParseForm() error

func (r *Request) ParseMultipartForm(maxMemory int64) error

func (r *Request) FormValue(key string) string

func (r *Request) PostFormValue(key string) string

func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)

func (r *Request) MultipartReader() (*multipart.Reader, error)

type Header

func (h Header) Get(key string) string

func (h Header) Set(key, value string)

func (h Header) Add(key, value string)

func (h Header) Del(key string)

func (h Header) Write(w io.Writer) error

func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error