這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
網上資料有點雜,有的還摻雜中介軟體進去,導致使用有障礙,所以,直接上官方文檔:
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 Requestfunc 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) boolfunc (r *Request) UserAgent() stringfunc (r *Request) Referer() stringfunc (r *Request) AddCookie(c *Cookie)func (r *Request) SetBasicAuth(username, password string)func (r *Request) Write(w io.Writer) errorfunc (r *Request) WriteProxy(w io.Writer) errorfunc (r *Request) Cookies() []*Cookiefunc (r *Request) Cookie(name string) (*Cookie, error)func (r *Request) ParseForm() errorfunc (r *Request) ParseMultipartForm(maxMemory int64) errorfunc (r *Request) FormValue(key string) stringfunc (r *Request) PostFormValue(key string) stringfunc (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)func (r *Request) MultipartReader() (*multipart.Reader, error)
type Headerfunc (h Header) Get(key string) stringfunc (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) errorfunc (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 Responsefunc ReadResponse(r *bufio.Reader, req *Request) (*Response, error)func (r *Response) ProtoAtLeast(major, minor int) boolfunc (r *Response) Cookies() []*Cookiefunc (r *Response) Location() (*url.URL, error)func (r *Response) Write([]byte) error//不同版本這個有差異
使用Write,資料轉化為byte即可。