예제 #1
0
// Get the media list
func (this *PmpMediaController) GetMediaList() {
	params := "fields:" + this.GetString("fields") + " ******* page: " + this.GetString("page") + " ****** rows:" + this.GetString("rows") + " **** sort:" +
		this.GetString("sort") + " ****** order:" + this.GetString("order") + " ****** name: " + this.GetString("name")
	beego.Info(params)
	name := this.GetString("name")
	page, _ := this.GetInt64("page")
	page_size, _ := this.GetInt64("rows")
	sort := this.GetString("sort")
	order := this.GetString("order")
	if len(order) > 0 {
		if order == "desc" {
			sort = " " + sort
		}
	} else {
		sort = "Id"
	}

	medias, count := models.GetMediaList(page, page_size, sort, name)
	if this.IsAjax() {
		this.Data["json"] = &map[string]interface{}{"total": count, "rows": &medias}
		jsoncontent, _ := json.Marshal(this.Data["json"])
		beego.Info("*********************" + string(jsoncontent) + "******************")
		this.ServeJson()
		return
	} else {
		//this.Data["json"] = &medias
		if this.GetTemplatetype() != "easyui" {
			this.Layout = this.GetTemplatetype() + "/public/layout.tpl"
		}
		this.TplNames = this.GetTemplatetype() + "/adspace/mediamanage.tpl"
	}
}
예제 #2
0
func (this *PmpDemandPlatformDeskController) UpdateDailyAllocation() {
	u := DemandVo{Day1: -1, Day2: -1, Day3: -1, Day4: -1, Day5: -1, Day6: -1, Day7: -1}
	if err := this.ParseForm(&u); err != nil {
		//handle error
		this.Rsp(false, err.Error())
		return
	}
	const layout = "2006-1-2"
	startdate, _ := time.Parse(layout, u.Operation)
	startdate = startdate.Local()
	var imps []int
	imps = append(imps, u.Day1)
	imps = append(imps, u.Day2)
	imps = append(imps, u.Day3)
	imps = append(imps, u.Day4)
	imps = append(imps, u.Day5)
	imps = append(imps, u.Day6)
	imps = append(imps, u.Day7)
	var datestrs []string
	for i := 0; i < 7; i++ {
		tempdate := startdate.AddDate(0, 0, i)
		datestrs = append(datestrs, tempdate.Format(layout))
	}
	beego.Info(" **** datestrs:", datestrs, " DemandAdspaceId: ", u.DemandAdspaceId, " imps: ", imps)
	num, err := models.UpdateImpByDemandAdpaceIdAndAdDate(u.DemandAdspaceId, u.Proportion, datestrs, imps)
	if err == nil {
		beego.Info(" **** Number of rows updated: ", num)
		this.Rsp(true, "Success")
		return
	} else {
		this.Rsp(false, err.Error())
		return
	}

}
예제 #3
0
파일: login.go 프로젝트: tcdog001/szm_lss
func (this *LoginController) Post() {
	//get form info
	uname := this.Input().Get("uname")
	pwd := this.Input().Get("pwd")

	admin := models.Admininfo{
		Username: uname,
		Password: pwd,
	}
	//check username and password
	ok := models.CheckAdmin(&admin)
	if ok {
		beego.Info("user/pwd matched!")

		this.SetSession("Admin", uname)
		if models.UpdateAdminStatus(&admin) {
			beego.Info("UpdateAdminStatus success!")
		} else {
			beego.Info("UpdateAdminStatus failed!")
		}

		beego.Info("Login success!")

		this.Data["IsMatched"] = true
		this.Redirect("/home", 301)
		return
	}

	beego.Info("Login failed! Once again!")
	this.Data["IsMatched"] = false
	this.Redirect("/login", 302)

	return
}
예제 #4
0
func (this *UserController) Reg() {

	beego.Info("register controller")
	result := make(map[string]interface{})
	result["succ"] = "succ"

	email := this.GetString("email")
	pwd := this.GetString("pwd")

	beego.Info(email)
	beego.Info(pwd)

	u := new(models.User)
	u.Email = email
	u.Pwd = helper.MD5(pwd)
	u.Reged = time.Now()
	u.Uname = email

	id, err := models.SaveUser(u)
	if err != nil {
		beego.Error(err)
		result["succ"] = "err"
	} else {
		result["id"] = u.Pwd
		result["email"] = email
	}
	this.SetSession("online_user", "u_"+strconv.FormatInt(id, 10))
	this.SetSession("online_user_email", email)

	this.Data["json"] = result
	this.ServeJson()
}
예제 #5
0
//realiza una consulta  en la base y devuelve el numero de filas
//para las paginaciones
func PagSql(tbl, pi, regxp string) (int, []orm.Params) {
	o := orm.NewOrm()
	o.Using("default")
	var maps []orm.Params
	var num int

	if tbl == "proveedor" {
		_, err := o.Raw(`SELECT SQL_CALC_FOUND_ROWS * 
    FROM proveedor LIMIT ` + pi + `,` + regxp).Values(&maps)
		o.Raw(`SELECT FOUND_ROWS()`).QueryRow(&num)
		if err != nil {
			beego.Info(err)
		}
	} else if tbl == "articulos" {
		//usamos una consulta join para poner datos en pagina
		_, err := o.Raw(`SELECT articulos.id,articulos.id_proveedor,
    articulos.ref_propia,articulos.descripcion,categoria.categoria 
    FROM articulos JOIN categoria WHERE articulos.id_categoria=
    categoria.id ORDER BY articulos.id  LIMIT ` + pi + `,` + regxp).Values(&maps)
		o.Raw(`SELECT FOUND_ROWS()`).QueryRow(&num)
		if err != nil {
			beego.Info(err)
		}
	}
	return num, maps
}
예제 #6
0
파일: import.go 프로젝트: tcdog001/szm_lss
func (this *ImportController) Post() {
	//check islogin
	session := this.GetSession("Admin")
	if session == nil {
		beego.Trace("session verify failed!")
		this.Redirect("/", 302)
		return
	}

	saveFileName := "temp" + strconv.FormatInt(int64(time.Now().UnixNano()), 10) + ".xlsx"
	beego.Debug("saveFileName=", saveFileName)

	this.SaveToFile("file", saveFileName)

	devices := make([]models.Deviceinfo, 0)

	xlFile, err := xlsx.OpenFile(saveFileName)
	if err != nil {
		beego.Error("Open excel file!", err)
	}
	for _, sheet := range xlFile.Sheets {
		for _, row := range sheet.Rows {
			for _, cell := range row.Cells {
				device := models.Deviceinfo{
					Mac:         cell.String(),
					ImportTime:  time.Now(),
					InvalidTime: time.Now().Add(3 * 30 * 24 * time.Hour),
				}
				//check mac address format
				if !CheckMacFormat(device.Mac) {
					beego.Info(device.Mac, "not a mac address!")
					continue
				}
				//if the mac address had existed,skip it
				if models.ImportDeviceCheck(&device) {
					beego.Info(device.Mac, "had been imported!")
					continue
				}
				devices = append(devices, device)
			}
		}
	}
	//delete used file
	err = os.Remove(saveFileName)
	if err != nil {
		beego.Error("Remove temp excel file failed!", err)
	}

	ok := models.ImportDevices(&devices)
	if ok {
		beego.Info("ImportDevices success!")
		this.Redirect("/home", 301)
		this.Data["IsImported"] = true
		return
	} else {
		beego.Info("ImportDevices failed! once again")
		this.Redirect("/import", 302)
		return
	}
}
예제 #7
0
파일: weibo.go 프로젝트: starchou/workspace
func http_call(req *http.Request, v interface{}) (bool, error) {
	if req.Method == "POST" {
		if req.Header.Get("Content-Type") == "" {
			req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		}
	}

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		beego.Info("fetch url %s %s", req.RequestURI, err)
		panic(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode == 200 {
		d := json.NewDecoder(resp.Body)
		err = d.Decode(&v)
		if err != nil {
			panic(err)
		}
		return true, err
	} else {
		bytes, _ := ioutil.ReadAll(resp.Body)
		beego.Info("Weibo API Error: " + string(bytes))
		var e WeiboError
		err = json.Unmarshal(bytes, &e)
		if err != nil {
			panic(err)
		}
		return false, e
	}
	return false, err
}
예제 #8
0
파일: models.go 프로젝트: sunvim/codelab
func init() {
	//读取配置文件
	getConfig()
	//初始化postgres数据库
	DbConn()
	if Orm.Ping() != nil {
		beego.Error("业务数据库连接不正常")
	} else {
		beego.Info("业务数据库连接正常")
	}
	if WorldOrm.Ping() != nil {
		beego.Error("用户中心数据库连接不正常")
	} else {
		beego.Info("用户中心数据库连接正常")
	}
	//创建表
	Orm.CreateTables(new(GameUser))
	//用户中心数据库控制表
	WorldOrm.CreateTables(new(UserControl), new(BizConfig), new(ErrorCode))
	WorldOrm.CreateTables(new(SystemConfig), new(ServList))

	InitSession = Orm.NewSession()
	err := InitSession.Begin()
	if err != nil {
		beego.Error("开启事务失败")
	}
	beego.Info("ORM 初始化成功!")
}
예제 #9
0
파일: busiPool.go 프로젝트: sunvim/codelab
//申请服务器列表
func (this *BusiData) ApplyServList() {
	beego.Info("ApplyServList ==> begin")
	worldSession := models.WorldOrm.NewSession()
	defer worldSession.Close()
	err := worldSession.Begin()
	if err != nil {
		beego.Error("开启事务失败:=>", err)
	}
	defer worldSession.Commit()
	var servList []models.ServList
	err = worldSession.Where("status='0' and serv_type='online'").Find(&servList)
	if err != nil {
		beego.Error("获取服务器列表失败=>", err)
		this.Response.Set("retCode", ERR_QUERY)
		return
	}
	busiInfo := gjson.New()
	var srvList []*gjson.Json
	for _, v := range servList {
		tempNode := gjson.New()
		tempNode.Set("servAddr", v.ServAddr)
		tempNode.Set("servPort", v.ServPort)
		tempNode.Set("servIndex", v.ServIndex)
		tempNode.Set("servDesc", v.ServDesc)
		srvList = append(srvList, tempNode)
	}
	busiInfo.Set("servList", srvList)
	this.Response.Set("busiInfo", busiInfo)
	this.Response.Set("retCode", RET_SUCC)
	beego.Info("ApplyServList ==> end")
	return
}
예제 #10
0
파일: main.go 프로젝트: thanzen/identity
func main() {
	setting.Initialize()
	beego.SetLogFuncCall(true)
	beego.SetViewsPath("views")

	if setting.IsProMode {
		beego.Info(setting.PostgresMigrateConnection)
		//auto migrate db
		//todo: we may want to disable this later
		//dbMigrate()
	} else {
		beego.Info("Develment mode enabled")
	}
	dbMigrate()
	beego.Info(beego.BConfig.AppName, setting.APP_VER, setting.AppUrl)
	testOnly() //todo:remove this
	//dev directory listing
	if !setting.IsProMode {
		beego.SetStaticPath("/assets", "static/dist/assets")
		beego.BConfig.WebConfig.DirectoryIndex = true
	}
	orm.RegisterDriver("postgres", orm.DRPostgres)

	orm.RegisterDataBase("default", "postgres", setting.PostgresConnection)
	services.Register()
	orm.RunCommand()
	orm.Debug = true

	controllers.RegisterControllers()

	if beego.BConfig.RunMode == "dev" {
		//	beego.Router("/test/:tmpl(mail/.*)", new(base.TestRouter))
	}
	beego.Run()
}
예제 #11
0
/**
 * 获取http请求结果,只支持post,返回结构自定义
 * url:请求地址
 * params:post参数
 * data:返回数据
 */
func GetPostHttpRequestData(url string, params map[string]string, respData interface{}) (err error) {
	defer func() {
		if x := recover(); x != nil {
			errStr := fmt.Sprintf("get post fail: params-%v , err-%v", params, x)
			err = errors.New(errStr)
		}
	}()
	begin := time.Now().UnixNano()
	req := httplib.Post(url).SetTimeout(CONNECT_TIME_OUT, READ_WRITE_TIME_OUT).Header("Content-Type", "application/x-www-form-urlencoded")
	beego.Info("Request url:", url, params)
	if params != nil && len(params) > 0 {
		for key, value := range params {
			req.Param(key, value)
		}
	}

	err = req.ToJson(respData)
	if err != nil {
		return
	}
	end := time.Now().UnixNano()
	beego.Info("Http response:", respData, ", cost:", end-begin)

	return
}
예제 #12
0
파일: web_client.go 프로젝트: ilahsa/go
///添加讨论组消息
func AddDGMessage(dg_msg message.DGMessage) int {
	client := &Client{}
	url := Config_Data_URL //"http://10.1.9.102/fbddc/api/api.php"

	json, _ := json.Marshal(dg_msg)
	beego.Info("web req is ", string(json))
	b := strings.NewReader(string(json))

	req, err := NewRequest("POST", url, b)
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("UU-REQUEST-MODULE", "messaging")
	req.Header.Add("UU-REQUEST-ACTION", "add_discussion_messages")
	req.Header.Add("UU-AUTH-TYPE", "2")
	if err != nil {
		//return nil
		fmt.Println(err)
	}

	response, err := client.Do(req)

	if err != nil {
		beego.Info("add_dgmsg error", err)
		return 500
	}
	beego.Info("web response is ", response)
	status := response.Header.Get("UU-Response-RC")
	if response.StatusCode == 200 && status == "0" {

		return 200
	}

	return 500
}
예제 #13
0
func (c *Collector) StopInterval(app *models.MonitorApp) {
	beego.Info("StopInterval invoke start" + strconv.Itoa(app.Id))
	if err := gm.StopLoopGoroutine(strconv.Itoa(app.Id)); err != nil {
		beego.Error(err)
	}
	beego.Info("StopInterval invoke end")
}
예제 #14
0
파일: attch.go 프로젝트: sunvim/codelab
func (this *AttachController) Post() {
	var (
		attachment string
		fileExist  string
	)
	// 获取文件名
	_, fh, err := this.GetFile("updatePack")
	if err != nil {
		beego.Error(err)
	}
	if fh != nil {
		//验证文件是否已存在
		attachment = fh.Filename
		fileExist = path.Join("updatePack", attachment)
		beego.Info("filePath: ", fileExist)
		if _, err = os.Stat(fileExist); err == nil {
			this.Ctx.Output.Body([]byte("文件已存在"))
			beego.Info("上传文件已存在")
			return
		}
		// 保存文件
		err = this.SaveToFile("updatePack", fileExist)
		if err != nil {
			beego.Error(err)
		}
	}
	this.Ctx.Output.Body([]byte("OK"))
	//解压缩并生成更新列表
	go UnzipUpdatePack(attachment)
	return
}
예제 #15
0
파일: heartbeat.go 프로젝트: tcdog001/LMS
func (this *HeartBeatController) Post() {
	ret := HeartData{}
	//用户认证
	uname, pwd, ok := this.Ctx.Request.BasicAuth()
	if !ok {
		beego.Info("get client  Request.BasicAuth failed!")
		ret.Code = -1
		writeContent, _ := json.Marshal(ret)
		this.Ctx.WriteString(string(writeContent))
		return
	}
	user := models.Userinfo{
		Username: uname,
		Password: pwd,
	}
	ok = models.CheckAccount(&user)
	if !ok {
		beego.Info("user/pwd not matched!")
		ret.Code = -1
		writeContent, _ := json.Marshal(ret)
		this.Ctx.WriteString(string(writeContent))
		return
	}
	beego.Info("user/pwd matched!")

	//接收请求信息
	beego.Debug("requestBody=", string(this.Ctx.Input.RequestBody))
	deviceinfo := models.Deviceinfo{}
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &deviceinfo)
	beego.Debug("deviceinfo=", deviceinfo)
	if err != nil {
		beego.Error(err)
		ret.Code = -2
		writeContent, _ := json.Marshal(ret)
		this.Ctx.WriteString(string(writeContent))
		return
	}

	//心跳接收成功,更新设备状态
	deviceinfo.State = 1
	deviceinfo.LastKeepaliveTime = time.Now()
	if !models.UpdateDeviceStatus(&deviceinfo) {
		ret.Code = -2
		writeContent, _ := json.Marshal(ret)
		this.Ctx.WriteString(string(writeContent))
		return
	}

	//插入Listener中
	device := DeviceListener{
		State:         1,
		LastAliveTime: time.Now(),
	}
	Listener[deviceinfo.Mac] = device

	//返回给设备处理结果
	ret.Code = 0
	writeContent, _ := json.Marshal(ret)
	this.Ctx.WriteString(string(writeContent))
}
예제 #16
0
/**
 * Delete the user, by their id, if that user's available.
 */
func (manage *ManageController) Delete() {
	manage.Layout = "basic-layout.tpl"
	manage.LayoutSections = make(map[string]string)
	manage.LayoutSections["Header"] = "header.tpl"
	manage.LayoutSections["Footer"] = "footer.tpl"
	manage.TplNames = "manage/home.tpl"

	// convert the string value to an int
	articleId, _ := strconv.Atoi(manage.Ctx.Input.Param(":id"))

	o := orm.NewOrm()
	o.Using("default")

	article := models.Article{}

	// Check if the article exists first
	if exist := o.QueryTable(article.TableName()).Filter("Id", articleId).Exist(); exist {
		if num, err := o.Delete(&models.Article{Id: articleId}); err == nil {
			beego.Info("Record Deleted. ", num)
		} else {
			beego.Error("Record couldn't be deleted. Reason: ", err)
		}
	} else {
		beego.Info("Record Doesn't exist.")
	}
}
예제 #17
0
func (this *MainController) Post() {
	body, err := ioutil.ReadAll(this.Ctx.Request.Body)
	if err != nil {
		beego.Error(err)
		this.Ctx.ResponseWriter.WriteHeader(500)
		return
	}
	beego.Info(string(body))
	var wreq *Request
	if wreq, err = DecodeRequest(body); err != nil {
		beego.Error(err)
		this.Ctx.ResponseWriter.WriteHeader(500)
		return
	}
	beego.Info(wreq.Content)
	wresp, err := dealwith(wreq)
	if err != nil {
		beego.Error(err)
		this.Ctx.ResponseWriter.WriteHeader(500)
		return
	}
	data, err := wresp.Encode()
	if err != nil {
		beego.Error(err)
		this.Ctx.ResponseWriter.WriteHeader(500)
		return
	}
	this.Ctx.WriteString(string(data))
	return
}
예제 #18
0
파일: topic.go 프로젝트: xmvper/golang-blog
func (this *TopicController) FileAdd() {
	this.Ctx.Request.ParseMultipartForm(32 << 20)
	file, _, err := this.Ctx.Request.FormFile("file")
	if err != nil {
		beego.Error("[上传文件错误]" + err.Error())
	}
	defer file.Close()
	datas, err := ioutil.ReadAll(file)
	fmt.Println("fmt", datas)
	if err != nil {
		beego.Error("[读取文件错误]" + err.Error())
	}

	beego.Info(string(datas) + "[datas]")

	a := string(datas)
	result := string(blackfriday.MarkdownBasic(datas))
	result = strings.Replace(result, "<code>", "<code class=\"go\">", -1)
	// this.Ctx.WriteString(string(datas)) 为什么这里不输出

	beego.Info(a)

	this.Data["json"] = result
	this.ServeJson()
}
예제 #19
0
파일: migration.go 프로젝트: ngaut/beego
// Reset reset all migration
// run all migration's down function
func Reset() error {
	sm := sortMap(migrationMap)
	i := 0
	for j := len(sm) - 1; j >= 0; j-- {
		v := sm[j]
		if isRollBack(v.name) {
			beego.Info("skip the", v.name)
			time.Sleep(1 * time.Second)
			continue
		}
		beego.Info("start reset:", v.name)
		v.m.Reset()
		v.m.Down()
		err := v.m.Exec(v.name, "down")
		if err != nil {
			beego.Error("execute error:", err)
			time.Sleep(2 * time.Second)
			return err
		}
		i++
		beego.Info("end reset:", v.name)
	}
	beego.Info("total success reset:", i, " migration")
	time.Sleep(2 * time.Second)
	return nil
}
예제 #20
0
파일: login.go 프로젝트: tcdog001/szm_lms
func (this *LoginController) Post() {
	//获取表单内容
	uname := this.Input().Get("uname")
	pwd := this.Input().Get("pwd")

	admin := models.Admininfo{
		Username: uname,
		Password: pwd,
	}
	//在数据库中做匹配
	ok := models.CheckAdmin(&admin)
	if ok {
		beego.Info("user/pwd matched!")

		this.SetSession("Admin", uname)
		if models.UpdateAdminStatus(&admin) {
			beego.Info("UpdateAdminStatus success!")
		} else {
			beego.Info("UpdateAdminStatus failed!")
		}
		beego.Info("Login success!")

		//登录成功,重定向到主页面
		this.Data["IsMatched"] = true
		path := "/home?CurUser="******"Login failed! Once again!")
	this.Data["IsMatched"] = false
	this.Redirect("/login/?ShowError=true", 302)
	return
}
예제 #21
0
파일: modify.go 프로젝트: tcdog001/szm_lss
func (this *ModifyController) Post() {
	///check islogin
	session := this.GetSession("Admin")
	if session == nil {
		beego.Trace("session verify failed!")
		this.Redirect("/", 302)
		return
	}
	//get form info
	mac := this.Input().Get("mac")
	newmac := this.Input().Get("newmac")

	deviceinfo := models.Deviceinfo{
		Mac: mac,
	}

	//check mac address format
	if !CheckMacFormat(newmac) {
		beego.Error(newmac, "not a mac address!")
		router := "/modify?mac="
		router += mac
		this.Redirect(router, 302)
		return
	}
	//write to db
	ok := models.ModifyDevice(&deviceinfo, newmac)
	if ok {
		beego.Info("ModifyDevice success!")
		this.Redirect("/noregister", 301)
		return
	}
	beego.Info("ModifyDevice failed! Once again")
	this.Data["HadModified"] = false
}
예제 #22
0
파일: wetalk.go 프로젝트: varding/wetalk
func main() {
	initialize()

	beego.Info("AppPath:", beego.AppPath)

	if setting.IsProMode {
		beego.Info("Product mode enabled")
	} else {
		beego.Info("Develment mode enabled")
	}
	beego.Info(beego.AppName, setting.APP_VER, setting.AppUrl)

	//initialize the routers
	routers.Initialize()
	if !setting.IsProMode {
		beego.SetStaticPath("/static_source", "static_source")
		beego.DirectoryIndex = true
	}

	if beego.RunMode == "dev" {
		//enable debug for orm
		//orm.Debug = false
		orm.Debug = true
	}

	// For all unknown pages.
	beego.Run()
}
예제 #23
0
파일: index.go 프로젝트: sshitaime/myblog
func (this *MainController) Get() {
	page, err := this.GetInt64("p", 1)
	if err != nil {
		beego.Error(err)
	}

	extend := map[string]string{}
	tid := this.GetString("tid", "")
	key := this.GetString("key")
	if tid != "" {
		extend["type_id"] = tid
	}

	beego.Info(extend)
	maps, err := models.GetArtPageList(10, (page-1)*10, extend, key)

	if err != nil {
		beego.Error(err)
	}
	count, err := models.GetCount(extend, key)
	if err != nil {
		beego.Error(err)
	}
	p := pagination.NewPaginator(this.Ctx.Request, 10, count)
	beego.Info(p)
	this.Data["paginator"] = p
	types := models.GetAllType()
	this.Data["articles"] = maps
	this.Data["types"] = types
	this.Data["key"] = key
	beego.AppConfig.String("banner1.name")

	this.TplNames = "index.tpl"
}
예제 #24
0
func main() {
	initialize()

	if utils.IsProMode {
		beego.Info("Product mode enabled")
	} else {
		beego.Info("Development mode enabled")
	}
	beego.Info(beego.AppName, utils.APP_VER, utils.AppUrl)

	if !utils.IsProMode {
		beego.SetStaticPath("/static_source", "static_source")
	}

	// Register routers.

	general := new(routers.GeneralRouter)
	beego.Router("/", general, "get:PublicHome")
	beego.Router("/home", general, "get:UserHome")
	beego.Router("/acknowledgements", general, "get:Acknowledgements")

	user := new(routers.UserRouter)
	beego.Router("/u/:email", user, "get:Home")

	login := new(routers.LoginRouter)
	beego.Router("/login", login, "post:Login")
	beego.Router("/logout", login, "get:Logout")

	register := new(routers.RegisterRouter)
	beego.Router("/register", register, "post:Register")
	beego.Router("/active/success", register, "get:ActiveSuccess")
	beego.Router("/active/:code([0-9a-zA-Z]+)", register, "get:Active")

	settings := new(routers.SettingsRouter)
	beego.Router("/settings/profile", settings, "get:Profile;post:ProfileSave")

	forgot := new(routers.ForgotRouter)
	beego.Router("/forgot", forgot)
	beego.Router("/reset/:code([0-9a-zA-Z]+)", forgot, "get:Reset;post:ResetPost")

	adminDashboard := new(routers.AdminDashboardRouter)
	beego.Router("/admin", adminDashboard)

	routes := map[string]beego.ControllerInterface{
		"user": new(routers.UserAdminRouter),
		//Can place more routers to also use generic List/Save/Update/Delete urls below
	}
	for name, router := range routes {
		beego.Router(fmt.Sprintf("/admin/:model(%s)", name), router, "get:List")
		beego.Router(fmt.Sprintf("/admin/:model(%s)/:id(new)", name), router, "get:Create;post:Save")
		beego.Router(fmt.Sprintf("/admin/:model(%s)/:id([0-9]+)", name), router, "get:Edit;post:Update")
		beego.Router(fmt.Sprintf("/admin/:model(%s)/:id([0-9]+)/:action(delete)", name), router, "get:Confirm;post:Delete")
	}

	// "robot.txt"
	beego.Router("/robot.txt", &routers.RobotRouter{})

	// For all unknown pages.
	beego.Run()
}
예제 #25
0
파일: admin.go 프로젝트: 11101171/violence
func (this *AdminController) AgentOperate() {
	if this.Ctx.Input.Method() == "GET" {
		agentId := this.Ctx.Input.Param(":agentId")
		beego.Info("agentId", agentId)

		agent := &models.Agent{}
		if agentId != "" {
			agent = agent.SelectOneById(agentId)
		}
		this.Data["AgentForm"] = agent
		this.Layout = "layout/main.html"
		this.TplNames = "admin/agent/operate.html"
	} else {
		agent := &models.Agent{}
		if err := this.ParseForm(agent); err != nil {
			this.Data["jons"] = err
			this.ServeJson()
			return
		}

		agent.UserId = this.GetAuthUser().Id
		var valid *validation.Validation
		if agent.Id == "" {
			valid = agent.ValidAgentAdd()
		} else {
			valid = agent.ValidAgentEdit()
		}

		b, _ := valid.Valid(agent)
		if !b {
			this.Data["ErrorMap"] = valid.ErrorMap()
			this.Data["ErrorForm"] = agent
			for k, v := range valid.ErrorMap() {
				beego.Info(k, " Error is ", "-", v.Value, "-", v.Field, "-", v.Tmpl, "-", v.Key, "=", v.Message, "-")
			}
			this.Layout = "layout/main.html"
			this.TplNames = "admin/agent/operate.html"
			return
		}

		var message string
		if agent.Id == "" {
			message = "新增ssh成功"
			if err := agent.InsertOne(); err != nil {
				this.ErrDataBase("新增ssh失败")
				return
			}
		} else {
			message = "更新ssh成功"
			if err := agent.UpdateOne(); err != nil {
				this.ErrDataBase("更新ssh失败")
				return
			}
		}

		this.DoSuccess(message, "/admin/agent/list")

	}
}
예제 #26
0
파일: admin.go 프로젝트: 11101171/violence
// @router /user/operate/?:userId [get,post]
func (this *AdminController) UserOperate() {
	if this.Ctx.Input.Method() == "GET" {
		userId := this.Ctx.Input.Param(":userId")
		beego.Info("userId", userId)

		user := &models.User{}
		if userId != "" {
			user = user.SelectOneById(userId)
		}
		this.Data["UserForm"] = user
		this.Layout = "layout/main.html"
		this.TplNames = "admin/user/operate.html"
		return
	} else {
		user := &models.User{}
		if err := this.ParseForm(user); err != nil {
			this.Data["jons"] = err
			this.ServeJson()
			return
		}
		var valid *validation.Validation
		if user.Id == "" {
			valid = user.ValidUserAdd()
		} else {
			valid = user.ValidUserEdit()
		}

		b, _ := valid.Valid(user)
		if !b {
			this.Data["ErrorMap"] = valid.ErrorMap()
			this.Data["ErrorForm"] = user
			for k, v := range valid.ErrorMap() {
				beego.Info(k, " Error is ", "-", v.Value, "-", v.Field, "-", v.Tmpl, "-", v.Key, "=", v.Message, "-")
			}
			this.Layout = "layout/main.html"
			this.TplNames = "admin/user/operate.html"
			return
		}

		var message string
		if user.Id == "" {
			message = "新增用户成功"
			if err := user.InsertOne(); err != nil {
				this.ErrDataBase("新增用户失败")
				return
			}
		} else {
			message = "更新用户成功"
			if err := user.UpdateOne(); err != nil {
				this.ErrDataBase("更新用户失败")
				return
			}
		}

		this.DoSuccess(message, "/admin/user/list")
	}

}
예제 #27
0
파일: topic.go 프로젝트: xmvper/golang-blog
// 查找文章
func (this *TopicController) Query() {
	keyword := this.GetString("keyword")
	beego.Info("keyword", keyword)
	topicDAO := &models.TopicDAO{}
	topics := topicDAO.Query(keyword)
	this.TplNames = "topic/list.html"
	beego.Info(topics)
	this.Data["topics"] = topics
}
예제 #28
0
func main() {
	// 初始化系统参数
	beego.Info("Start init houserent system...")
	initialize()
	beego.Info("Init system successful")

	beego.Info("Start houserent system server...")
	beego.Run()
}
예제 #29
0
func (ctx *ChecklistController) AddNewChecklist() {

	if ctx.Ctx.Input.Method() == "POST" {
		checklist := models.Checklist{}

		if err := ctx.ParseForm(&checklist); err != nil {
			error := map[string]string{"status": "ERROR", "errorMsg": "An error occured. We couldn't parse the request"}
			ctx.Data["json"] = &error
			ctx.ServeJson()
		} else {
			checklist.Description = ctx.Input().Get("description")
			id, err := checklist.Save()

			if err != nil {
				error := map[string]string{"status": "ERROR", "msg": "An error occured while accessing the database."}
				ctx.Data["json"] = &error
				ctx.ServeJson()
			} else if id > 0 {
				t := make([]string, 0, 2)
				ctx.Ctx.Input.Bind(&t, "tasks")

				taskInsertionError := ""

				for _, elem := range t {
					tasks := new(models.Task)

					tasks.Description = elem
					tasks.Checklist_id = id
					tasks.Status = "0"

					beego.Info(tasks)
					_, err := tasks.Save()
					if err != nil {
						beego.Info(tasks)
						taskInsertionError = taskInsertionError + fmt.Sprintf("%s", err)
					}
				}
				if taskInsertionError == "" {
					success := map[string]string{"status": "SUCCESS", "msg": "Everything went according to plan"}
					ctx.Data["json"] = &success
					ctx.ServeJson()
				} else {
					tasks := new(models.Task)
					tasks.DeleteBatch("checklist_id", string(id))

					c := models.Checklist{Id: id}
					c.Delete()

					error := map[string]string{"status": "ERROR", "msg": "An error occured while accessing the database so we rolled everything back", "actualError": taskInsertionError}
					ctx.Data["json"] = &error
					ctx.ServeJson()
				}
			}

		}
	}
}
예제 #30
0
파일: alarm.go 프로젝트: tcdog001/LMS
func (this *AlarmController) Post() {
	ret := AlarmData{}
	//用户身份认证
	uname, pwd, ok := this.Ctx.Request.BasicAuth()
	if !ok {
		beego.Info("get client  Request.BasicAuth failed!")
		ret.Code = -1
		writeContent, _ := json.Marshal(ret)
		this.Ctx.WriteString(string(writeContent))
		return
	}
	user := models.Userinfo{
		Username: uname,
		Password: pwd,
	}
	ok = models.CheckAccount(&user)
	if !ok {
		beego.Info("user/pwd not matched!")
		ret.Code = -1
		writeContent, _ := json.Marshal(ret)
		this.Ctx.WriteString(string(writeContent))
		return
	}
	beego.Info("user/pwd matched!")

	//获取设备post数据
	beego.Info("request body=", string(this.Ctx.Input.RequestBody))
	alarm := models.Alarm{
		Time: time.Now(),
	}
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &alarm)
	if err != nil {
		beego.Error(err)
		ret.Code = -2
		writeContent, _ := json.Marshal(ret)
		this.Ctx.WriteString(string(writeContent))
		return
	}

	//将alarm信息写入数据库
	ok = models.AddAlarm(&alarm)
	if !ok {
		ret.Code = -2
		writeContent, _ := json.Marshal(ret)
		this.Ctx.WriteString(string(writeContent))
		return
	}

	//通知客户端进行报警

	//返回成功
	ret.Code = 0
	writeContent, _ := json.Marshal(ret)
	this.Ctx.WriteString(string(writeContent))
	beego.Info(string(writeContent))
	return
}