golang http

golang http

http 掛載方法

  • Head 發(fā)送 HEAD 請求

    func Head(url string) (resp *Response, err error)
    
  • Get 發(fā)送 GET 請求

    func Get(url string) (resp *Response, err error)
    
    res, _ := http.Get("http://www.baidu.com")
    
      defer res.Body.Close()
    
      if res.StatusCode == 200 {
          buf, _ := ioutil.ReadAll(res.Body)
          fmt.Println(string(buf))
      }
    
  • Post 發(fā)送 POST 請求

    func Post(url string, bodyType string, body io.Reader) (resp *Response, err error)
    
    url := "http://www.baidu.com"
      res, _ := http.Post(url, "json", nil)
      buf, _ := ioutil.ReadAll(res.Body)
      fmt.Println(string(buf))
    
  • Handle 向 http.DefaultServeMax 注冊路由方法

    func Handle(pattern string, handler Handler)
    
type MyHandler string

func (m MyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  w.Write([]byte(m))
}

func main() {

  var msg MyHandler = "show me"
  http.Handle("/", msg)

  http.ListenAndServe(":8080", nil)
}

  • HandleFunc 向 http.DefaultServeMax 注冊路由方法

    func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
    
      http.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
          w.Write([]byte("hello Rogan"))
      })
    
      http.ListenAndServe(":8080", nil)
    
    
  • Serve 開啟監(jiān)聽服務(wù), 服務(wù)底層接口

    func Serve(l net.Listener, handler Handler) error
    
    
  • ListenAndServe 監(jiān)聽指定地址的 TCP 服務(wù), 既創(chuàng)建 tcp 服務(wù), Serve 的上層接口

    func ListenAndServe(addr string, handler Handler) error
    
    
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
          w.Write([]byte("Hello"))
      })
    
      http.ListenAndServe(":8080", nil)
    
    
  • ListenAndServeTLS 開啟 https 服務(wù)

    func ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) error
    
    
  • FileServer 開啟靜態(tài)資源服務(wù)

    func ServeFile(w ResponseWriter, r *Request, name string)
    
    
      http.Handle("/", http.FileServer(http.Dir("./")))
      http.ListenAndServe(":8080", nil)
    
    
    
  • Redirect 重定向

    func Redirect(w ResponseWriter, r *Request, urlStr string, code int)
    
    
    
      http.HandleFunc("/product", func(w http.ResponseWriter, r *http.Request) {
          w.Write([]byte("to baidu"))
          http.Redirect(w, r, "http://www.baidu.com", 200)
      })
      http.ListenAndServe(":8080", nil)
    
    
    
  • Error 回復(fù)指定錯誤

    func Error(w ResponseWriter, error string, code int)
    
    
    http.HandleFunc("/product", func(w http.ResponseWriter, r *http.Request) {
          http.Error(w, "服務(wù)器錯誤", 500)
      })
      http.ListenAndServe(":8080", nil)
    
    
  • NotFound 返回404錯誤

    func NotFound(w ResponseWriter, r *Request)
    
    
    http.HandleFunc("/product", http.NotFound)
      http.ListenAndServe(":8080", nil)
    
    
  • SetCookie 設(shè)置Cookie

    func SetCookie(w ResponseWriter, cookie *Cookie)
    
    
    http.HandleFunc("/product", func(w http.ResponseWriter, r *http.Request) {
    
          cookie := http.Cookie{
              Name:   "uId",
              Value:  "111",
              MaxAge: 100,
          }
          
             // 請求返回前設(shè)置 cookie
          http.SetCookie(w, &cookie)
          w.Write([]byte("設(shè)置 Cookie"))
    
      })
    
    

Server 服務(wù)器掛載方法

  • serve 服務(wù)監(jiān)聽 與 http.Serve 一致
  • ListenAndServe 開啟 TCP 服務(wù)
  • ListenAndServeTLS 開啟 HTTPS 服務(wù)

Server 服務(wù)器屬性

  • Addr tcp 地址
  • Handler ServeMux 處理器
  • ReadTImeout 讀取超時
  • WriteTimeout 寫入超時
  • MaxHeaderBytes 最大請求頭長度
  • ConnState 設(shè)置日志記錄器
  • ErrorLog 非導(dǎo)出字段

ServeMux 路由掛載函數(shù)

  • NewServeMux 新建路由

    func NewServeMux() *ServeMux
    
    
  • Handle 掛載處理器

    func (mux *ServeMux) Handle(pattern string, handler Handler)
    
    
  • HandleFunc 掛載處理器

    func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
    
    
  • Handler 返回請求對應(yīng)的處理器

    func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)
    
    
  • ServeHTTP 分發(fā)請求

    func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)
    
    

ServeMux and Server 簡單例子

router := http.NewServeMux()
    server := http.Server{}

    router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

        w.Write([]byte("home page"))

    })

    server.Addr = ":8080"
    server.Handler = router

    server.ListenAndServe()

Client 客戶端掛載方法

  • Head 發(fā)送 Head 請求

    func (c *Client) Head(url string) (resp *Response, err error)
    
    
  • Get 發(fā)送 GET 請求

    func (c *Client) Get(url string) (resp *Response, err error)
    
    
  • Post 發(fā)送 POST 請求

    func (c *Client) Post(url string, bodyType string, body io.Reader) (resp *Response, err error)
    
    
  • Do 通用請求方法

    func (c *Client) Do(req *Request) (resp *Response, err error)
    
    
      req, _ := http.NewRequest("GET", "http://www.baidu.com", nil)
      client := &http.Client{}
      res, _ := client.Do(req)
    
      defer res.Body.Close()
    
      data, _ := ioutil.ReadAll(res.Body)
    
      fmt.Println(string(data))
    
    

快捷Handler

  • NotFoundHandler 404

    func NotFoundHandler() Handler
    
    
  • RedirectHandler 重定向

    func RedirectHandler(url string, code int) Handler
    
    
  • TimeoutHandler 超時

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容