package main
import (
"encoding/json"
"fmt"
_ "github.com/go-sql-driver/mysql"
"html/template"
"log"
"math/rand"
"net/http"
"webIm/model"
"webIm/service"
)
func userLogin(writer http.ResponseWriter, request *http.Request) {
request.ParseForm()
mobile := request.PostForm.Get("mobile")
passwd := request.PostForm.Get("passwd")
loginok := false
if mobile == "13648871148" && passwd == "123456"{
loginok = true
}
//str := `{"code":-1 , "msg":"密码错误"}`
if loginok {
//str = `{"code":0 , "data":{"id":1,"token":"test"}}`
data := make(map[string]interface{})
data["id"] = 1
data["token"] = "test"
Resp(writer,0,data,"")
}else {
Resp(writer,-1,nil,"密码错误")
}
//go get github.com/go-xorm/xorm
//go get github.com/go-sql-driver/mysql
//Resp(writer,0,data,"")
//io.WriteString(writer,"hello word !")
}
var userService service.UserService
func userRegister(writer http.ResponseWriter, request *http.Request) {
request.ParseForm()
mobile := request.PostForm.Get("mobile")
passwd := request.PostForm.Get("passwd")
sex := model.SexNukown
avatar := ""
nickname := fmt.Sprintf("user%06d",rand.Int31n(100000))
user,err := userService.Register(mobile,passwd,nickname,avatar,sex)
if err != nil {
Resp(writer,-1,nil,err.Error())
}else {
Resp(writer,0,user,err.Error())
}
}
type H struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data",omitempty`
}
func Resp(writer http.ResponseWriter,code int,data interface{},msg string) {
writer.Header().Set("Content-Type","application/json")
writer.WriteHeader(http.StatusOK)
h := H{
Code: code,
Msg: msg,
Data: data,
}
ret , err := json.Marshal(h)
if err != nil{
log.Println(err.Error())
}
writer.Write(ret)
}
func RegisterView() {
tpl,err := template.ParseGlob("viies/**/*")
if err != nil{
log.Fatal(err.Error())
}
for _,v := range tpl.Templates(){
tplname := v.Name()
http.HandleFunc(tplname, func(w http.ResponseWriter, request *http.Request) {
tpl.ExecuteTemplate(w,tplname,nil)
})
}
}
func main() {
//绑定请求和处理函数
http.HandleFunc("/user/login",userLogin)
http.HandleFunc("/user/register",userRegister)
//http.Handle("/",http.FileServer(http.Dir(".")))
http.Handle("/static/",http.FileServer(http.Dir(".")))
//启动服务器
//http.HandleFunc("/user/login.shtml", func(w http.ResponseWriter, request *http.Request) {
// tpl,err := template.ParseFiles("viies/user/login.html")
// if err != nil{
// log.Fatal(err.Error())
// }
// tpl.ExecuteTemplate(w,"/user/login.shtml",nil)
//})
RegisterView()
http.ListenAndServe(":8080",nil)
}