Go語言實現HTTP伺服器並解析header參數和表單參數

來源:互聯網
上載者:User

Go語言實現HTTP伺服器並解析header參數和表單參數

在http服務裡,header參數和表單參數是經常使用到的,本文主要是練習在Go語言裡,如何解析Http請求的header裡的參數和表單參數,具體代碼如下:

package server
 
import (
  "net/http"
  "strconv"
  "fmt"
)
 
func HttpStart(port int)  {
  http.HandleFunc("/hello", helloFunc)
  err := http.ListenAndServe(":"+strconv.Itoa(port), nil)
  if err != nil {
      fmt.Println("監聽失敗:",err.Error())
  }
}
 
func helloFunc(w http.ResponseWriter, r *http.Request)  {
  fmt.Println("列印Header參數列表:")
  if len(r.Header) > 0 {
      for k,v := range r.Header {
        fmt.Printf("%s=%s\n", k, v[0])
      }
  }
  fmt.Println("列印Form參數列表:")
  r.ParseForm()
  if len(r.Form) > 0 {
      for k,v := range r.Form {
        fmt.Printf("%s=%s\n", k, v[0])
      }
  }
  //驗證使用者名稱密碼,如果成功則header裡返回session,失敗則返回StatusUnauthorized狀態代碼
  w.WriteHeader(http.StatusOK)
  if (r.Form.Get("user") == "admin") && (r.Form.Get("pass") == "888") {
      w.Write([]byte("hello,驗證成功!"))
  } else {
      w.Write([]byte("hello,驗證失敗了!"))
  }
}

運行後,在chrom瀏覽器裡執行請求:http://127.0.0.1:8001/hello?user=admin&pass=888,服務端會列印參數列表如下:
列印Header參數列表:

Accept-Language=zh-CN,zh;q=0.9
Connection=keep-alive
Cache-Control=max-age=0
Upgrade-Insecure-Requests=1
User-Agent=Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.19 Safari/537.36
Accept=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding=gzip, deflate, br
列印Form參數列表:
user=admin
pass=888

並且會返回成功結果給用戶端的,瀏覽器裡運行結果為:

如果瀏覽器裡不是請求/hello則會報404,如果參數寫其他的也會返回驗證失敗的結果!

本文永久更新連結地址:https://www.bkjia.com/Linux/2018-03/151166.htm

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.