1 package main
2
3 import (
4 "fmt"
5 "html/template"
6 "net/http"
7 "strings"
8 "log"
9 _ "github.com/go-sql-driver/mysql"
10 "database/sql"
11 )
12
13 type WebMux struct{
14 }
15
16 func (p *WebMux) ServeHTTP(w http.ResponseWriter,r *http.Request){
17 switch r.URL.Path{
18 case "/":
19 sayHello(w,r)
20 return
21 case "/login":
22 login(w,r)
23 return
24 default:
25 http.NotFound(w,r)
26 return
27 }
28 }
29
30 func checkErr(err error) {
31 if err != nil {
32 panic(err)
33 }
34 }
35
36 func sayHello(w http.ResponseWriter,r *http.Request){
37 r.ParseForm()
38 fmt.Println(r.Form)
39 fmt.Println("path:",r.URL.Path)
40 fmt.Println("scheme:",r.URL.Scheme)
41 fmt.Println(r.Form["url_long"])
42 for k,v:=range r.Form{
43 fmt.Println("key:",k)
44 fmt.Println("val:",strings.Join(v," "))
45 }
46 fmt.Fprintf(w,"Hello,welcome to Go web world!")
47 }
48
49 func login(w http.ResponseWriter,r *http.Request){
50 fmt.Println("method:",r.Method)
51 if r.Method=="GET" {
52 t,_:=template.ParseFiles("gtpl/login.gtpl")
53 t.Execute(w,nil)
54 } else {
55 r.ParseForm()
56 fmt.Println("username:",r.Form["username"][0])
57 fmt.Println("password:",r.Form["password"][0])
58
59 //连接数据库
60 dbConnStr:="xoops:xoops@tcp(ubuntu_tst:3306)/xoops?charset=utf8"
61 db,err:=sql.Open("mysql",dbConnStr)
62 defer db.Close()
63 rows,err:=db.Query("select * from auth_user where password=? and username=?",r.Form["password"][0],r.Form["username"][0])
64 checkErr(err)
65 if rows.Next() {
66 var username,password,usercnname string
67 rows.Scan(&username,&password,&usercnname)
68 fmt.Fprintf(w,"Hello,%s",usercnname)
69 } else {
70 fmt.Fprintf(w,"Ooooops!Invalid username or password.")
71 }
72 }
73 }
74 func main(){
75 //http.HandleFunc("/",sayHello)
76 //err:=http.ListenAndServe(":9090",nil)
77 mux:=&WebMux{}
78 err:=http.ListenAndServe(":9090",mux)
79 if err!=nil {
80 log.Fatal("ListenAndServe:",err)
81 }
82 }