go的net/http包使用

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

網上資料有點雜,有的還摻雜中介軟體進去,導致使用有障礙,所以,直接上官方文檔:

    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即可。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.