吾八哥博客

您现在的位置是:首页 > 码农手记 > Golang > 正文

Golang

Golang里实现Http服务器并解析header参数和表单参数

吾八哥2018-02-20Golang9566

在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

并且会返回成功结果给客户端的,浏览器里运行结果为:

QQ图片20180228235530.png

如果浏览器里不是请求/hello则会报404,如果参数写其他的也会返回验证失败的结果!