Golang验证Form输入

此类文章都是从网上收集整理。

本文是对网页中的Form数据进行验证。

golang的源代码:

  1 package main
  2 
  3 import (
  4     "fmt"
  5     "html/template"
  6     "log"
  7     "net/http"
  8     "regexp"
  9     "strconv"
 10     "strings"
 11     "time"
 12 )
 13 
 14 type MyMux struct {
 15 }
 16 
 17 func (p *MyMux) ServeHTTP(res http.ResponseWriter, req *http.Request) {
 18     if req.URL.Path == "/" {
 19         SayHi(res, req)
 20         return
 21     } else if req.URL.Path == "/login" {
 22         Login(res, req)
 23         return
 24     }
 25 
 26     http.NotFound(res, req)
 27     return
 28 }
 29 
 30 func SayHi(res http.ResponseWriter, req *http.Request) {
 31     fmt.Fprint(res, "Hello World")
 32 }
 33 
 34 func Login(res http.ResponseWriter, req *http.Request) {
 35     if req.Method == "GET" {
 36         t, _ := template.ParseFiles("login.html")
 37         log.Println(t.Execute(res, nil))
 38         //fmt.Fprint(res, req.Form["username"], req.Form["password"])
 39     } else {
 40         if len(req.FormValue("username")) == 0 {
 41             fmt.Fprint(res, "用户名不能为空")
 42             fmt.Fprint(res, "\npassword: ", req.FormValue("password"))
 43             return
 44         }
 45         // if m, _ := regexp.MatchString("^[0-9]+$", req.Form.Get("age")); !m { return false }
 46         age, err := strconv.Atoi(req.Form.Get("age"))
 47         if err != nil {
 48             fmt.Fprint(res, "年龄请输入数值")
 49             return
 50         }
 51         if age > 140 || age < 0 {
 52             fmt.Fprint(res, "年龄取值范围在0 ~ 140岁之间")
 53             return
 54         }
 55         if m, _ := regexp.MatchString("^\\p{Han}+$", req.Form.Get("realname")); !m {
 56             fmt.Fprint(res, "真实的姓名不是汉字")
 57             return
 58         }
 59         if m, _ := regexp.MatchString("^[a-zA-Z]+$", req.Form.Get("engname")); !m {
 60             fmt.Fprint(res, "英文名字输入的不是英文")
 61             return
 62         }
 63         if m, _ := regexp.MatchString(`^([\w\.\_]{2,10})@(\w{1,}).([a-z]{2,4})$`, req.Form.Get("email")); !m {
 64             fmt.Fprint(res, "电子邮件格式不正确")
 65             return
 66         }
 67         if m, _ := regexp.MatchString(`^(1[3|4|5|8][0-9]\d{4,8})$`, req.Form.Get("mobile")); !m {
 68             fmt.Fprint(res, "您输入的不是手机号码")
 69             return
 70         }
 71         slice1 := []string{"apple", "pear", "banane"}
 72         found1 := false
 73         v1 := req.Form.Get("fruit")
 74         for _, item := range slice1 {
 75             if item == v1 {
 76                 found1 = true
 77                 break
 78             }
 79         }
 80         if found1 == false {
 81             fmt.Fprint(res, "系统发现您在伪造下拉菜单中不存在的选项")
 82             return
 83         }
 84 
 85         slice2 := []int{1, 2}
 86         found2 := false
 87         for _, v2 := range slice2 {
 88             gender, err := strconv.Atoi(req.Form.Get("gender"))
 89             if err == nil && v2 == gender {
 90                 found2 = true
 91                 break
 92             }
 93         }
 94         if found2 == false {
 95             fmt.Fprint(res, "系统发现您在伪造选项中不存在的选项")
 96             return
 97         }
 98 
 99         m := map[string]int{"football": 0, "basketball": 1, "tennis": 2}
100         found3 := false
101         for _, sport := range req.Form["interest"] {
102             _, exist := m[sport]
103             if exist == false {
104                 found3 = true
105                 break
106             }
107         }
108         if found3 == true {
109             fmt.Fprint(res, "系统发现您在伪造复选框选项")
110             return
111         }
112 
113         mytime, err := String2Time(req.Form.Get("txtDateTime"))
114         if err != nil {
115             fmt.Fprint(res, "您输入的不是日期时间格式的数据")
116             return
117         }
118 
119         //验证15位身份证,15位的是全部数字
120         if m, _ := regexp.MatchString(`^(\d{15})$`, req.Form.Get("id1card")); !m {
121             fmt.Fprint(res, "您输入的不是15位身份证号码")
122             return
123         }
124         //验证18位身份证,18位前17位为数字,最后一位是校验位,可能为数字或字符X
125         if m, _ := regexp.MatchString(`^(\d{17})([0-9]|X)$`, req.Form.Get("id2card")); !m {
126             fmt.Fprint(res, "您输入的不是18位身份证号码")
127             return
128         }
129         //请求的是登陆数据,那么执行登陆的逻辑判断
130         req.ParseForm()                                // req.FormValue("username") 调用req.FormValue时会自动调用req.ParseForm,所以不必提前调用
131         fmt.Println("username:", req.Form["username"]) //必需提前调用req.ParseForm()
132         fmt.Println("password:", req.Form["password"])
133 
134         fmt.Fprint(res, "\n username:", req.Form["username"][0], "    ", "password:", req.Form["password"][0])
135         fmt.Fprint(res, "\n age:", age)
136         fmt.Fprint(res, "\n Real Name:", req.Form.Get("realname"))
137         fmt.Fprint(res, "\n English Name:", req.Form.Get("engname"))
138         fmt.Fprint(res, "\n Email:", req.Form.Get("email"))
139         fmt.Fprint(res, "\n Mobile:", req.Form.Get("mobile"))
140         fmt.Fprint(res, "\n Fruit:", req.Form.Get("fruit"))
141         fmt.Fprint(res, "\n Gender:", req.Form.Get("gender"))
142         fmt.Fprint(res, "\n Interests:", req.Form["interest"])
143         fmt.Fprint(res, "\n txtDateTime: ", mytime)
144         fmt.Fprint(res, "\n 15位身份证: ", req.Form.Get("id1card"))
145         fmt.Fprint(res, "\n 18位身份证: ", req.Form.Get("id2card"))
146     }
147 }
148 
149 func main() {
150     mux := &MyMux{}
151     http.ListenAndServe(":8080", mux) // http://127.0.0.1:8080/login
152 }
153 
154 func String2Time(in string) (out time.Time, err error) {
155     in = strings.Replace(in, "/", "-", -1)
156     fmt.Println(in)
157     if len(in) > 10 {
158         out, err = time.Parse("2006-01-02 15:04:05", in) //layout使用"2006/01/02 15:04:05"此数据格式转换会出错
159     } else {
160         out, err = time.Parse("2006-01-02", in) //layout使用"2006/01/02"此数据格式转换会出错
161     }
162     return out, err
163 }

对应的模板文件:

 1 <!Doctype html>
 2 <html>
 3     <head>
 4         <title></title>
 5     </head>
 6     <body>
 7         <form action="/login" method="post">
 8             用户名:<input type="text" name="username"><br>
 9             密码:<input type="password" name="password"><br>
10             <input type="submit" value="登陆"><br>
11             <hr>
12             Age:<input type="text" name="age"><br>
13             Real Name:<input type="text" name="realname"><br>
14             English Name:<input type="text" name="engname"><br>
15             Email:<input type="text" name="email"><br>
16             Mobile:<input type="text" name="mobile"><br>
17             <select name="fruit">
18                 <option value="apple">apple</option>
19                 <option value="pear">pear</option>
20                 <option value="banana">banana</option>
21             </select><br>
22             <input type="radio" name="gender" value="1"><br>
23             <input type="radio" name="gender" value="2"><br>
24             <input type="checkbox" name="interest" value="football">足球 <br>
25             <input type="checkbox" name="interest" value="basketball">篮球 <br>
26             <input type="checkbox" name="interest" value="tennis">网球 <br>
27             日期时间:<input type="text" name="txtDateTime"><br>
28             身份证(15位):<input type="text" name="id1card"><br>
29             身份证(18位):<input type="text" name="id2card"><br>
30         </form>
31     </body>
32 
33 </html>

猜你喜欢

转载自www.cnblogs.com/merrynuts/p/13207708.html
今日推荐