网上资料有点杂,有的还掺杂中间件进去,导致使用有障碍,所以,直接上官方文档:
1,首先搞清[]byte string的相互转换,最简单的方式就是
string转[]byte:[]byte(para string)
[]byte转string:string([]byte)
然后还有就是io包的一些实现方式,比如:
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
其中,Body的类型是io.read,head的类型是 map[string][]string,所以,获取获取方式都不一样:
获取Body:io.ioutil.ReadAll(req.Body),返回[]byte类型的数据,一般多用于json
获取header:req.Header.get("para")
获取form中数据:req.ParseForm,然后,para=PostFormValue("para")
3,给请求返回数据:
response的数据结构比较简单:
type Response
func ReadResponse(r *bufio.Reader, req *Request) (*Response, error)
func (r *Response) ProtoAtLeast(major, minor int) bool
func (r *Response) Cookies() []*Cookie
func (r *Response) Location() (*url.URL, error)
func (r *Response) Write([]byte) error//不同版本这个有差异
使用Write,数据转化为byte即可。
有疑问加站长微信联系(非本文作者)