Exemplo n.º 1
0
/**
* 删除表的某行(多行)记录
* delete from tableName where whereState
**/
func Delete(tableName string, whereState string) bool {
	if tableName == "" {
		logger.Println(tag_DBUtil, "Delete tableName is nil")
		return false
	}
	if db == nil {
		logger.Println(tag_DBUtil, "Delete, db is nil")
		return false
	}
	var mysql string = "delete from " + tableName
	if whereState != "" {
		mysql += " where " + whereState
	}
	stmt, err := db.Prepare(mysql)
	if err != nil {
		logger.Println(tag_DBUtil, err)
		return false
	}
	_, err = stmt.Exec()
	if err != nil {
		logger.Println(tag_DBUtil, err)
		return false
	}
	return true
}
Exemplo n.º 2
0
/*
*执行一个sql语句,sql中的变量用?代替,用?代替的值全部放在value数组中
**/
func ExcuteSql(sql string, value []interface{}) (driver.Result, bool) {
	if sql == "" {
		logger.Println(tag_DBUtil, "ExcuteSql sql is nil")
		return nil, false
	}
	if db == nil {
		logger.Println(tag_DBUtil, "ExcuteSql, db is nil")
		return nil, false
	}
	stmt, err := db.Prepare(sql)
	if err != nil {
		logger.Println(tag_DBUtil, err)
		return nil, false
	}
	var result driver.Result
	if len(value) < 1 {
		result, err = stmt.Exec()
	} else {
		result, err = stmt.Exec(value...)
	}
	if err != nil {
		logger.Println(tag_DBUtil, err)
		return nil, false
	}
	return result, true
}
Exemplo n.º 3
0
/*
启动websocket服务器ws://localhost:8888
*/
func startWs() {
	logger.Println("main", "start websocket port 8888")
	err := http.ListenAndServe(":8888", &customWSMux{})
	if err != nil {
		logger.Println("main", err)
	}
}
Exemplo n.º 4
0
func ServeHTTP(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()                           //解析参数,默认是不会解析的
	logger.Println(tag_customRoute, r.Form) //这些信息是输出到服务器端的打印信息
	logger.Println(tag_customRoute, "path:"+r.URL.Path)
	logger.Println(tag_customRoute, "Scheme:"+r.URL.Scheme)
	logger.Println(tag_customRoute, "Proto:"+r.Proto)
	doHttp(w, r)
}
Exemplo n.º 5
0
func ServeWebSocket(w http.ResponseWriter, r *http.Request) {
	logger.Println(tag_customRoute, "ServeWebSocket")
	conn, err := upgrader.Upgrade(w, r, nil)
	defer conn.Close()
	if err != nil {
		logger.Println(tag_customRoute, err)
		return
	}
	doWebSocket(w, r, conn)
}
Exemplo n.º 6
0
/**
* 初始化数据库连接
* driverName:驱动名称,如"mysql"
* dataSourceName:它是go-sql-driver定义的一些数据库链接和配置信息。它支持如下格式:
* user@unix(/path/to/socket)/dbname?charset=utf8
* user:password@tcp(localhost:5555)/dbname?charset=utf8
* user:password@/dbname
* user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname
**/
func Init(driverName string, dataSourceName string) error {
	var err error
	db, err = sql.Open(driverName, dataSourceName)
	if err != nil {
		logger.Println(tag_DBUtil, err)
		return err
	}
	err = db.Ping()
	if err != nil {
		logger.Println(tag_DBUtil, err)
		return err
	}
	return nil
}
Exemplo n.º 7
0
/*
http页面路由
*/
func doHttp(w http.ResponseWriter, r *http.Request) {
	var path string = r.URL.Path
	if path == "/" {
		Login(w, r)
		return
	} else if path == "/login" {
		Login(w, r)
	} else if path == "/register" {
		Register(w, r)
	} else if path == "/upload" {
		Upload(w, r)
	} else if path == "/ajax" {
		OnAjax(w, r)
	} else if strings.HasPrefix(path, "/static/") || strings.HasPrefix(path, "static/") {
		file := "template/static" + r.URL.Path[len("/static"):]
		f, err := os.Open(file)
		defer f.Close()
		if err != nil && os.IsNotExist(err) {
			logger.Println(tag_customRoute, err)
		}
		http.ServeFile(w, r, file)
		return
	} else {
		http.NotFound(w, r)
	}
}
Exemplo n.º 8
0
/*
websocket接收发送消息
*/
func doWebSocket(w http.ResponseWriter, r *http.Request, conn *websocket.Conn) {
	for {
		var inputData []byte
		msgType, inputData, err := conn.ReadMessage()
		if err != nil {
			logger.Println(tag_customRoute, err)
			return
		}
		logger.Println(tag_customRoute, "receive data:"+string(inputData))
		err = conn.WriteMessage(msgType, inputData)
		if err != nil {
			logger.Println(tag_customRoute, err)
			return
		}
	}
}
Exemplo n.º 9
0
func Register(w http.ResponseWriter, r *http.Request) {
	logger.Println(tag_regis, "Register")
	err := r.ParseForm()
	if err != nil {
		logger.Println(tag_regis, err)
	} //解析参数,默认是不会解析的
	logger.Println("method:", r.Method) //获取请求的方法
	if r.Method == "GET" {
		cookie, err := r.Cookie("login")
		var t *template.Template
		if err == nil && len(cookie.Value) > 0 {
			logger.Println(tag_lg, "cookie:"+cookie.Value)
			t, err = template.ParseFiles("template" + "/forum.html")
		} else {
			t, err = template.ParseFiles("template" + "/register.htm")
		}
		if err != nil {
			logger.Println(tag_lg, err)
			return
		}
		t.Execute(w, nil)
	} else if r.Method == "POST" {
		//请求的是登陆数据,那么执行登陆的逻辑判断
		r.ParseMultipartForm(10)
		logger.Println("form:", r.Form)
		logger.Println("username:"******"username"))
		logger.Println("password:"******"password"))
		name := r.FormValue("username")
		pwd := r.FormValue("password")
		isExist := dao.CheckUserName(name)
		if !isExist {
			state := dao.AddUser(name, pwd)
			if state == false {
				logger.Println(tag_regis, "addUser failed")
				fmt.Fprintf(w, "注册失败,请重新注册")
			} else {
				expiration := time.Now()
				expiration = expiration.Add(10 * time.Minute)
				//		stamp := utils.EncMd5(name + password)
				cookie := http.Cookie{
					Name:    "login",
					Value:   name,
					Expires: expiration}
				http.SetCookie(w, &cookie)
				fmt.Fprintf(w, "hello "+r.Form.Get("username"))
			}
		} else {
			fmt.Fprintf(w, name+" has existed")
		}
	}
}
Exemplo n.º 10
0
/*
启动http服务器,http://localhost:9090
*/
func startHttp() {
	logger.Println("main", "start http,listen on 9090 port")
	err := http.ListenAndServe(":9090", &customMux{})
	if err != nil {
		log.Println("main", err)
		log.Fatal("server error")
	}
}
Exemplo n.º 11
0
/**
*向user表中增加一条记录
 */
func AddUser(name string, password string) bool {
	if len(name) < 6 || len(password) < 6 {
		logger.Println(user, " name or password less 6 letter")
		return false
	}
	var property = []string{"name", "password"}
	values := []interface{}{name, password}
	state := dbutil.Insert("user_pwd", property, values)
	return state
}
Exemplo n.º 12
0
func Query(tableName string, propertys []string, whereState string, orderByState string, groupByState string) (*sql.Rows, bool) {
	if tableName == "" {
		logger.Println(tag_DBUtil, "Query tableName is nil")
		return nil, false
	}
	if db == nil {
		logger.Println(tag_DBUtil, "Query, db is nil")
		return nil, false
	}
	var mysql string
	if len(propertys) < 1 {
		mysql = "select * from " + tableName
	} else {
		mysql = "select "
		for i := 0; i < len(propertys); i++ {
			if i < len(propertys)-1 {
				mysql += propertys[i] + ","
			} else {
				mysql += propertys[i] + " from " + tableName
			}
		}
	}
	//where
	if whereState != "" {
		mysql += " where " + whereState
	}
	// order by
	if orderByState != "" {
		mysql += " order by " + orderByState
	}
	//group by
	if groupByState != "" {
		mysql += " group by " + groupByState
	}
	logger.Println(tag_DBUtil, mysql)
	rows, err := db.Query(mysql)
	if err != nil {
		logger.Println(tag_DBUtil, err)
		return nil, false
	}
	return rows, true
}
Exemplo n.º 13
0
/**
*检查用户名是否存在
 */
func CheckUserName(uname string) bool {
	var property []string = []string{"name"}
	rows, _ := dbutil.Query("user_pwd", property, "name = "+"'"+uname+"'", "", "")
	if rows == nil {
		return false
	}
	for rows.Next() {
		var name string
		err := rows.Scan(&name)
		if err != nil {
			logger.Println(err)
			continue
		}
		logger.Println(name)
		if uname == name {
			return true
		}
	}
	return false
}
Exemplo n.º 14
0
/**
*检查用户名密码是否正确
 */
func CheckUserPwd(uname string, pwd string) bool {
	var property []string = []string{"name", "password"}
	rows, _ := dbutil.Query("user_pwd", property, "name = "+"'"+uname+"'", "", "")
	if rows == nil {
		return false
	}
	for rows.Next() {
		var name string
		var password string
		err := rows.Scan(&name, &password)
		if err != nil {
			logger.Println(err)
			continue
		}
		logger.Println(name, password)
		if uname == name && password == pwd {
			return true
		}
	}
	return false
}
Exemplo n.º 15
0
/*
处理http /OnAjax 请求
*/
func OnAjax(w http.ResponseWriter, r *http.Request) {
	logger.Println(tag_customRoute, "OnAjax")
	r.ParseForm()
	//set cookie
	expiration := time.Now()
	expiration = expiration.Add(1 * time.Minute)
	cookie := http.Cookie{
		Name:    "login",
		Value:   r.Form.Get("username") + r.Form.Get("password") + r.Form.Get("token"),
		Expires: expiration}
	http.SetCookie(w, &cookie)
	io.WriteString(w, "恭喜你,登陆成功!")
}
Exemplo n.º 16
0
func Login(w http.ResponseWriter, r *http.Request) {
	logger.Println(tag_lg, "login")
	r.ParseForm()                       //解析参数,默认是不会解析的
	logger.Println("method:", r.Method) //获取请求的方法
	if r.Method == "GET" {
		cookie, err := r.Cookie("login")
		var t *template.Template
		if err == nil && len(cookie.Value) > 0 {
			logger.Println(tag_lg, "cookie:"+cookie.Value)
			t, err = template.ParseFiles("template" + "/forum.html")
		} else {
			t, err = template.ParseFiles("template" + "/login.htm")
		}
		if err != nil {
			logger.Println(tag_lg, err)
			return
		}
		t.Execute(w, nil)
	} else if r.Method == "POST" {
		//请求的是登陆数据,那么执行登陆的逻辑判断
		r.ParseMultipartForm(10)
		name := r.FormValue("username")
		pwd := r.FormValue("password")
		state := dao.CheckUserPwd(name, pwd)
		if state == true {
			//set cookie
			expiration := time.Now()
			expiration = expiration.Add(15 * time.Minute)
			cookie := http.Cookie{
				Name:    "login",
				Value:   name,
				Expires: expiration}
			http.SetCookie(w, &cookie)
			fmt.Fprintf(w, "登陆成功")
		} else {
			fmt.Fprintf(w, "登陆失败")
		}
	}
}
Exemplo n.º 17
0
// 处理/upload 逻辑
func Upload(w http.ResponseWriter, r *http.Request) {
	logger.Println("method:", r.Method) //获取请求的方法
	mycookie, err := r.Cookie("login")
	if err != nil || mycookie == nil {
		var prompt string = "not login or login timeout"
		logger.Println(tag_upload, prompt)
		w.Write([]byte(prompt))
		return
	}
	logger.Println(tag_upload, "mycookie Name:"+mycookie.Name+" value:"+mycookie.Value+" Expires:"+mycookie.Expires.String())
	if r.Method == "GET" {
		crutime := time.Now().Unix()
		h := md5.New()
		io.WriteString(h, strconv.FormatInt(crutime, 10))
		token := fmt.Sprintf("%x", h.Sum(nil))
		Separator := utils.GetSeparator()
		t, err := template.ParseFiles("template" + Separator + "testupload.html")
		if err != nil {
			logger.Println(tag_upload, err)
			return
		}
		t.Execute(w, token)
	} else {
		r.ParseMultipartForm(32 << 20)
		file, handler, err := r.FormFile("uploadfile")
		if err != nil {
			logger.Println(err)
			return
		}
		defer file.Close()
		fmt.Fprintf(w, "%v", handler.Header)
		var f *os.File
		var subpath string = "data"
		f, err = utils.CreatFile(subpath, handler.Filename)
		if err != nil {
			logger.Println(tag_upload, err)
			return
		}
		defer f.Close()
		io.Copy(f, file)
	}
}
Exemplo n.º 18
0
/**
* update tableName set property = values where whereProperty whereOpt whereValue
**/
func Update(tableName string, property []string, values []interface{}, whereProperty string, whereOpt string, whereValue interface{}) bool {
	if db == nil {
		logger.Println(tag_DBUtil, "Update, db is nil")
		return false
	}
	logger.Println(tag_DBUtil, property, values, whereProperty, whereValue)
	if len(property) < 1 || len(property) != len(values) {
		logger.Println(tag_DBUtil, "Update, property length is not equal values")
		return false
	}
	var mysql string = "update " + tableName + " set"
	for i := 0; i < len(property); i++ {
		if i == 0 {
			mysql += " " + property[i] + " = ?"
		} else {
			mysql += " ," + property[i] + " = ?"
		}
	}
	//where
	if whereProperty != "" && whereOpt != "" {
		mysql += " where " + whereProperty + " " + whereOpt + " ?"
	}
	logger.Println(tag_DBUtil, mysql)
	stmt, err := db.Prepare(mysql)
	if err != nil {
		logger.Println(tag_DBUtil, err)
		return false
	}
	if len(whereProperty) < 1 {
		_, err = stmt.Exec(values...)
	} else {
		newValue := append(values, whereValue)
		_, err = stmt.Exec(newValue...)
	}
	if err != nil {
		logger.Println(tag_DBUtil, err)
		return false
	}
	return true
}
Exemplo n.º 19
0
/**
*向表插入一条记录
* tableName:数据库表名
* property:属性名
* values:属性值
* bool:插入成功返回true,否则范湖false
**/
func Insert(tableName string, property []string, values []interface{}) bool {
	if db == nil {
		logger.Println(tag_DBUtil, "insert, db is nil")
		return false
	}
	logger.Println(tag_DBUtil, property, values)
	if len(property) < 1 || len(property) != len(values) {
		logger.Println(tag_DBUtil, "insert, property length is not equal values")
		return false
	}
	var mysql string = "insert into " + tableName + "("
	for i := 0; i < len(property); i++ {
		if i < len(property)-1 {
			mysql += property[i] + ","
		} else {
			mysql += property[i] + ")"
		}
	}
	mysql += " values("
	for i := 0; i < len(values); i++ {
		if i < len(values)-1 {
			mysql += "?,"
		} else {
			mysql += "?)"
		}
	}
	logger.Println(tag_DBUtil, mysql)
	stmt, err := db.Prepare(mysql)
	if err != nil {
		logger.Println(tag_DBUtil, err)
		return false
	}
	_, err = stmt.Exec(values...)
	if err != nil {
		logger.Println(tag_DBUtil, err)
		return false
	}
	return true
}
Exemplo n.º 20
0
/*
创建一个webSocket服务端(:8888)和一个http服务端(:9090)
*/
func main() {
	initApplication()
	releaseApplication()
	logger.Println(tag_hs, "main over")
}