//文件管理 func FilesManager(this *beego.Controller) { strRet := "" callbackjson := "{\"state\": \"SUCCESS\",\"list\": [" total := 0 err := filepath.Walk(uploadfile, func(path string, f os.FileInfo, err error) error { if f == nil { return err } if f.IsDir() { return nil } ext := path[strings.LastIndex(path, ".")+1:] if strings.Contains(allowFileType, ext) { strRet += (path + "ue_separate_ue") callbackjson += "{\"url\": \"/" + uploadfile + f.Name() + "\"}," total++ fmt.Println("allow:", path) } return nil }) if err != nil { fmt.Printf("filepath.Walk() returned %v\n", err) } callbackjson += "],\"start\": 0,\"total\": " + strconv.Itoa(total) + "}" fmt.Println(strRet) this.Ctx.WriteString(callbackjson) this.StopRun() }
// 解析数组 func (this *YuqingAnalyse) BaseFormStrings(contro *beego.Controller) (bool, interface{}) { types := contro.GetStrings("t") if len(types) > 0 { typeInts := make([]int, len(types)) for k, _ := range types { typeInts[k], _ = strconv.Atoi(types[k]) } this.Type = typeInts } ignoreTypes := contro.GetStrings("i") if len(ignoreTypes) > 0 { typeInts := make([]int, len(ignoreTypes)) for k, _ := range ignoreTypes { typeInts[k], _ = strconv.Atoi(ignoreTypes[k]) } this.IgnoreType = typeInts } return true, nil }
func UploadFile(this *beego.Controller) { //filename := this.Input().Get("Filename") f, h, _ := this.GetFile("upfile") filename := h.Filename f.Close() //关闭,减少缓存 index := strings.LastIndex(filename, ".") filetype := "" if index == -1 { this.Ctx.WriteString("{\"state\":\"FAILED\"}") this.StopRun() } filetype = filename[index:] ext := filetype[1:] if !strings.Contains(allowFileType, ext) { this.Ctx.WriteString("{\"state\":\"FAILED\"}") this.StopRun() } newname := strconv.FormatInt(time.Now().Unix(), 10) + "_" + filename err := this.SaveToFile("upfile", uploadfile+newname) state := "SUCCESS" if err != nil { fmt.Println(err) state = "FAILED" } url := website + uploadfile + newname this.Ctx.WriteString("{\"state\": \"" + state + "\", \"url\": \"" + url + "\", \"title\": \"\",\"original\": \"" + filename + "\"}") this.StopRun() }
/* 根据话题id判断是否为其管理员 */ func (this *GameController) isManagerById(contro *beego.Controller) (bool, *models.Topic, *models.Game, *models.Member) { //实例化话题 topic := &models.Topic{} ok := topic.FindById(contro.GetString("id")) if !ok { //不存在此话题 return false, nil, nil, nil } //获取游戏信息 game := &models.Game{} ok = game.FindPath(topic.Game) if ok { //存在此游戏 //获取用户信息 member := &models.Member{} if session := contro.GetSession("WOKUID"); session != nil { if ok := member.FindOne(session.(string)); ok { //如果是游戏管理员 if member.Id == game.Manager { return true, topic, game, member } else { return false, topic, game, member } } } } return false, nil, nil, nil }
/* 用户登陆,为用户建立session */ func (this *UserController) UserLogin(contro *beego.Controller) { //用户登陆次数加1 this.member.LogTime++ //保存用户信息 this.member.Save() //建立session contro.SetSession("WOKUID", this.member.Id.Hex()) }
// login user func LoginUser(user *User, c *beego.Controller, remember bool) { // weird way of beego session regenerate id... c.CruSession = beego.GlobalSessions.SessionRegenerateId(c.Ctx.ResponseWriter, c.Ctx.Request) c.Ctx.Input.CruSession = c.CruSession sess := c.StartSession() sess.Set("auth_user_id", user.Id) }
//carga las tpl-no me esta funcionando bn func LoadTpl(this *beego.Controller, s string, b bool) { this.Layout = "basic-layout.tpl" this.LayoutSections = make(map[string]string) this.LayoutSections["Header"] = "header.tpl" this.LayoutSections["Footer"] = "footer.tpl" this.Data["IsArtProv"] = b this.Data["place"] = "Busqueda por Id" this.Data["nombotton"] = "Buscar Id Prov" this.TplNames = s }
//提示错误页面 func EchoErrorPage(c *beego.Controller, message string, url string) { isGoback := false if url == "" { isGoback = true } c.Data["Message"] = message c.Data["Url"] = url c.Data["IsGoback"] = isGoback c.Layout = "admin/error.tpl" c.StopRun() }
/* 被动接收支付宝同步跳转的页面 */ func AlipayReturn(contro *beego.Controller) (int, string, string, string) { //列举全部传参 type Params struct { Body string `form:"body" json:"body"` //描述 BuyerEmail string `form:"buyer_email" json:"buyer_email"` //买家账号 BuyerId string `form:"buyer_id" json:"buyer_id"` //买家ID Exterface string `form:"exterface" json:"exterface"` //接口名称 IsSuccess string `form:"is_success" json:"is_success"` //交易是否成功 NotifyId string `form:"notify_id" json:"notify_id"` //通知校验id NotifyTime string `form:"notify_time" json:"notify_time"` //校验时间 NotifyType string `form:"notify_type" json:"notify_type"` //校验类型 OutTradeNo string `form:"out_trade_no" json:"out_trade_no"` //在网站中唯一id PaymentType uint8 `form:"payment_type" json:"payment_type"` //支付类型 SellerEmail string `form:"seller_email" json:"seller_email"` //卖家账号 SellerId string `form:"seller_id" json:"seller_id"` //卖家id Subject string `form:"subject" json:"subject"` //商品名称 TotalFee string `form:"total_fee" json:"total_fee"` //总价 TradeNo string `form:"trade_no" json:"trade_no"` //支付宝交易号 TradeStatus string `form:"trade_status" json:"trade_status"` //交易状态 TRADE_FINISHED或TRADE_SUCCESS表示交易成功 Sign string `form:"sign" json:"sign"` //签名 SignType string `form:"sign_type" json:"sign_type"` //签名类型 } //实例化参数 param := &Params{} //解析表单内容,失败返回错误代码-3 if err := contro.ParseForm(param); err != nil { return -3, "", "", "" } //如果最基本的网站交易号为空,返回错误代码-1 if param.OutTradeNo == "" { //不存在交易号 return -1, "", "", "" } else { //生成签名 sign := sign(param) //对比签名是否相同 if sign == param.Sign { //只有相同才说明该订单成功了 //判断订单是否已完成 if param.TradeStatus == "TRADE_FINISHED" || param.TradeStatus == "TRADE_SUCCESS" { //交易成功 return 1, param.OutTradeNo, param.BuyerEmail, param.TradeNo } else { //交易未完成,返回错误代码-4 return -4, "", "", "" } } else { //签名认证失败,返回错误代码-2 return -2, "", "", "" } } //位置错误类型-5 return -5, "", "", "" }
//上传图片 func WebUploadImage(this *beego.Controller) { //filename := this.Input().Get("Filename") f, h, _ := this.GetFile("Filedata") filename := h.Filename f.Close() //关闭,减少缓存 ext := filename[strings.LastIndex(filename, ".")+1:] //获取扩展名 if !strings.Contains(allowImageType, ext) { fmt.Println(filename) this.Ctx.WriteString("{\"state\":\"0\"}") this.StopRun() } newname := strconv.FormatInt(time.Now().Unix(), 10) + "_" + filename err := this.SaveToFile("Filedata", uploadimage+newname) state := "SUCCESS" if err != nil { fmt.Println(err) state = "0" } state = "1" url := website + uploadimage + newname //this.Ctx.WriteString("{'original':'" + filename + "','url':'" + url + "','title':'" + this.Input().Get("pictitle") + "','state':'" + state + "'}") //this.Ctx.WriteString("{\"state\": \"" + state + "\", \"url\": \"" + url + "\", \"title\": \"\",\"original\": \"" + filename + "\"}") this.Ctx.WriteString("{\"status\": " + state + ", \"msg\": \"上传文件成功!\", \"name\": \"1.jpg\", \"path\": \"" + url + "\", \"thumb\": \"" + url + "\", \"size\": 0, \"ext\": \"" + ext + "\"}") this.StopRun() }
func parseAccount(ctx *beego.Controller, account *models.Account) error { email := ctx.GetString("email") password := ctx.GetString("password") password2 := ctx.GetString("password2") name := ctx.GetString("name") showemail := ctx.GetString("showemail") var err error err = nil if email == "" { err = errors.New("email miss") return err } if password == "" || password != password2 { err = errors.New("password") return err } if name == "" { err = errors.New("name miss") return err } if showemail != "show" && showemail != "hide" { err = errors.New("showemail miss") return err } account.EMail = email account.Password = password account.DisplayName = name account.CreateTime = time.Now() account.LastLoginTime = time.Now() if showemail == "show" { account.ShowEmail = true } else { account.ShowEmail = false } account.Level = 0 return err }
/* 根据条件保存上传文件 */ func (this *ApiController) SaveFile(contro *beego.Controller, size int64, suf []string) (bool, string, int64) { //获取文件信息 f, h, err := contro.GetFile("file") if err != nil { UserLog.Error("文件上传失败:", err) f.Close() return false, "", 0 } f.Close() //保存文件到临时目录 contro.SaveToFile("file", "static/tmp/"+h.Filename) // 打开文件 fh, err := os.Open("static/tmp/" + h.Filename) if err != nil { return false, "", 0 } //获取文件具体信息 stat, _ := fh.Stat() if stat.Size() > size { //文件大小不合格,删除文件 //关闭文件 fh.Close() os.Remove("static/tmp/" + h.Filename) return false, "", 0 } nameSplit := strings.Split(h.Filename, ".") suffix := nameSplit[len(nameSplit)-1] ok := false //后缀不合格则删除文件 for _, v := range suf { if suffix == v { //符合其中一个后缀 ok = true } } if !ok { //关闭文件 fh.Close() os.Remove("static/tmp/" + h.Filename) return false, "", 0 } //关闭文件 fh.Close() return true, "static/tmp/" + h.Filename, stat.Size() //返回文件路径、大小 }
//远程抓图 func CatchImage(this *beego.Controller) { //fmt.Println(this.Ctx.Request.Body) urls := this.GetStrings("source[]") //fmt.Println(urls) callbackjson := "{\"state\": \"SUCCESS\",\"list\": [" if len(urls) > 0 { for _, v := range urls { //去掉最后的!后面部分 l := v //判断扩展名是否合法 ext := l[strings.LastIndex(l, ".")+1:] if strings.Contains(allowImageType, ext) { //获取文件名 filename := l[strings.LastIndex(l, "/")+1:] newname := strconv.FormatInt(time.Now().Unix(), 10) + "_" + filename res, err := http.Get(l) defer res.Body.Close() if err != nil { callbackjson += "{\"url\": \"\",\"source\": \"" + l + "\",\"state\": \"ERROR\"}," fmt.Println("Error:远程抓取失败;", err) } else { dst, err := os.Create(uploadimage + newname) if err != nil { callbackjson += "{\"url\": \"\",\"source\": \"" + l + "\",\"state\": \"ERROR\"}," fmt.Println("Error:保存失败;", err) } else { callbackjson += "{\"url\": \"" + uploadimage + newname + "\",\"source\": \"" + l + "\",\"state\": \"SUCCESS\"}," io.Copy(dst, res.Body) } } } else { callbackjson += "{\"url\": \"\",\"source\": \"" + l + "\",\"state\": \"ERROR\"}," } //fmt.Println(l) } } callbackjson += "]}" this.Ctx.WriteString(callbackjson) this.StopRun() return }
/* 判断用户是否是游戏管理员 */ func (this *GameController) isManager(contro *beego.Controller) (bool, *models.Game, *models.Member) { //获取游戏信息 game := &models.Game{} ok := game.FindPath(contro.GetString("category")) if !ok { return false, nil, nil } //获取用户信息 member := &models.Member{} if session := contro.GetSession("WOKUID"); session != nil { if ok := member.FindOne(session.(string)); ok { //如果不是这个游戏的管理员则无权限 if member.Id != game.Manager { return false, nil, nil } else { return true, game, member } } else { return false, nil, nil } } else { return false, nil, nil } }
//信息提示,如果异步,返回json、如果同步,则页面提示并返回 func EchoTip(c *beego.Controller, json *models.TipJSON) { if c.IsAjax() { //异步提交 c.Data["json"] = json c.ServeJson() c.StopRun() } else { tpl := "admin/error.tpl" if json.Status == models.TipSuccess { tpl = "admin/success.tpl" } c.Data["Tip"] = json c.Layout = tpl //此处不能用 c.StopRun() 返回,否则会空白页面! //c.StopRun() return } }
//上传图片 func UploadImage(this *beego.Controller) { f, h, _ := this.GetFile("upfile") filename := h.Filename f.Close() //关闭,减少缓存 //获取扩展名 ext := filename[strings.LastIndex(filename, ".")+1:] if !strings.Contains(allowImageType, ext) { fmt.Println(filename) this.Ctx.WriteString("{\"state\":\"FAILED\"}") this.StopRun() } newname := strconv.FormatInt(time.Now().Unix(), 10) + "_" + filename err := this.SaveToFile("upfile", uploadimage+newname) state := "SUCCESS" if err != nil { fmt.Println(err) state = "FAILED" } url := website + uploadimage + newname this.Ctx.WriteString("{\"state\": \"" + state + "\", \"url\": \"" + url + "\", \"title\": \"\",\"original\": \"" + filename + "\"}") this.StopRun() }
//判断是否登陆 func CheckAdminLogin(c *beego.Controller, t int64) { id, _ := c.GetSession("adminid").(int) username, _ := c.GetSession("adminname").(string) adminrole, _ := c.GetSession("adminrole").(int) if id == 0 || username == "" || adminrole == 0 { switch t { case 0: c.Redirect("/admin/login", 301) case 1: //返回JSON json := &models.TipJSON{} json.Status = models.TipError json.Message = "请先登录,再执行此操作" json.ReturnUrl = "/admin/login" c.Data["json"] = json c.ServeJson() c.StopRun() } } c.Data["AdminName"] = username c.Data["AdminId"] = id c.Layout = "admin/layout.tpl" }
// login user func LoginUser(user *User, c *beego.Controller, remember bool) { // werid way of beego session regenerate id... c.SessionRegenerateID() c.CruSession.Set("auth_user_id", user.Id) }
//获取广告内容 func GetAdsDetail(c *beego.Controller) string { str := "" tip := &models.TipJSON{} tip.Status = models.TipError tid, _ := strconv.ParseInt(c.GetString("Tid"), 10, 64) switch tid { case 0: //代码 script := &models.ScriptAds{} script.Content = c.GetString("txtScript") if script.Content == "" { tip.Message = "代码不能为空!" EchoTip(c, tip) } arrstr, _ := json.Marshal(script) str = string(arrstr) case 1: //文字 text := &models.TextAds{} text.Txt = c.GetString("txt_Txt") text.Link = c.GetString("txt_Txt") text.Style = c.GetString("txt_Style") if text.Txt == "" { tip.Message = "文字内容不能为空!" EchoTip(c, tip) } if text.Link == "" { tip.Message = "文字链接不能为空!" EchoTip(c, tip) } arrstr, _ := json.Marshal(text) str = string(arrstr) case 2: //图片类 img := &models.ImgAds{} img.Img = c.GetString("img_Img") img.Alt = c.GetString("img_Alt") img.Link = c.GetString("img_Link") img.Height, _ = strconv.ParseInt(c.GetString("img_Height"), 10, 64) img.Width, _ = strconv.ParseInt(c.GetString("img_Width"), 10, 64) if img.Img == "" { tip.Message = "图片地址不能为空!" EchoTip(c, tip) } if img.Link == "" { tip.Message = "图片链接不能为空!" EchoTip(c, tip) } arrstr, _ := json.Marshal(img) str = string(arrstr) case 3: //Flash flash := &models.FlashAds{} flash.Swf = c.GetString("flash_Swf") flash.Height, _ = strconv.ParseInt(c.GetString("flash_Height"), 10, 64) flash.Width, _ = strconv.ParseInt(c.GetString("flash_Width"), 10, 64) if flash.Swf == "" { tip.Message = "Flash 地址不能为空!" EchoTip(c, tip) } arrstr, _ := json.Marshal(flash) str = string(arrstr) case 4: //幻灯片 sw, _ := strconv.ParseInt(c.GetString("slide_Width"), 10, 64) sh, _ := strconv.ParseInt(c.GetString("slide_Height"), 10, 64) SImg := c.GetStrings("slide_Img") SLink := c.GetStrings("slide_Link") SAlt := c.GetStrings("slide_Alt") if len(SImg) <= 0 { tip.Message = "幻灯片图片不能为空!" EchoTip(c, tip) } if len(SLink) <= 0 { tip.Message = "幻灯片图片链接不能为空!" EchoTip(c, tip) } length := len(SImg) listImg := []*models.ImgAds{} for i := 0; i < length; i++ { tmp := models.ImgAds{} if SImg[i] != "" && SLink[i] != "" { tmp.Img = SImg[i] tmp.Link = SLink[i] tmp.Alt = SAlt[i] tmp.Height = sh tmp.Width = sw listImg = append(listImg, &tmp) } } if listImg == nil || len(listImg) <= 0 { tip.Message = "幻灯片请最少设置一个图片!" EchoTip(c, tip) } arrstr, _ := json.Marshal(listImg) str = string(arrstr) } return str }
func Config(this *beego.Controller) { //this.ServeJson(configJson) this.Ctx.WriteString(string(configJson)) this.StopRun() }
// logout user func LogoutUser(c *beego.Controller) { c.CruSession.Delete("auth_user_id") c.DestroySession() }
// 解析数组 func (this *Member) BaseFormStrings(contro *beego.Controller) (bool, interface{}) { this.Power = contro.GetStrings("po") return true, nil }
// logout user func LogoutUser(c *beego.Controller) { sess := c.StartSession() sess.Delete("auth_user_id") c.DestroySession() }
/* 后台操作数据表 */ func Restful(this BaseInterface, contro *beego.Controller) { ok, data := func() (bool, interface{}) { switch contro.GetString("type") { case "add": //增 if err := contro.ParseForm(this); err != nil { return false, err.Error() } //数据验证 valid := validation.Validation{} b, err := valid.Valid(this) if err != nil { return false, "验证参数解析失败" } if !b { //验证失败 for _, err := range valid.Errors { return false, err.Key + " " + err.Message } } // 额外解析数组参数 if _ok, _data := this.BaseFormStrings(contro); !_ok { return false, _data } if err := this.BaseInsert(); err != nil { return false, err.Error() } return true, "" // 插入成功 case "delete": //删 if _ok, _data := this.BaseSetId(contro.GetString("_id")); !_ok { return false, _data } err := this.BaseDelete() if err != nil { return false, err } return true, nil case "update": //改 //根据id查询对象 if _ok, _data := this.BaseFind(contro.GetString("_id")); !_ok { return false, _data } //解析请求参数->对象 if err := contro.ParseForm(this); err != nil { return false, err.Error() } // 额外解析数组参数 if _ok, _data := this.BaseFormStrings(contro); !_ok { return false, _data } //验证 valid := validation.Validation{} b, err := valid.Valid(this) if err != nil { return false, "验证参数解析失败" } if !b { //验证失败 for _, err := range valid.Errors { return false, err.Key + " " + err.Message } } if err := this.BaseUpdate(); err != nil { return false, err.Error() } return true, nil case "get": //查 from, _ := contro.GetInt("from") number, _ := contro.GetInt("number") if number > 100 { return false, "最多查询100条" } if contro.GetString("like") != "" && contro.GetString("likeKey") != "" { // 模糊搜索 var result []BaseInterface var count int if contro.GetString("likeMethod") == "like" { result = this.BaseSelectLike(from, number, contro.GetString("sort"), contro.GetString("likeKey"), contro.GetString("like")) count = this.BaseLikeCount(contro.GetString("likeKey"), contro.GetString("like")) } else if contro.GetString("likeMethod") == "accuracy" { result = this.BaseSelectAccuracy(from, number, contro.GetString("sort"), contro.GetString("likeKey"), contro.GetString("like")) count = this.BaseAccuracyCount(contro.GetString("likeKey"), contro.GetString("like")) } return true, map[string]interface{}{ "lists": result, "count": count, } } else { // 普通查询 if contro.GetString("filter") != "" { filter, _ := contro.GetInt("filter") count := this.BaseFilterCount(contro.GetString("filterKey"), filter) result := this.BaseFilterSelect(from, number, contro.GetString("sort"), contro.GetString("filterKey"), filter) return true, map[string]interface{}{ "lists": result, "count": count, } } else { count := this.BaseCount() result := this.BaseSelect(from, number, contro.GetString("sort")) return true, map[string]interface{}{ "lists": result, "count": count, } } } } return true, nil }() contro.Data["json"] = map[string]interface{}{ "ok": ok, "data": data, } contro.ServeJson() }