コード例 #1
0
// @Title createUser
// @router / [post]
func (h *UserController) Post() {
	defer h.ServeJSON()
	user := new(models.Users)
	err := json.Unmarshal(h.Ctx.Input.RequestBody, user)
	if err != nil {
		beego.Warn("[C] Got error:", err)
		h.Data["json"] = map[string]string{
			"message": "Bad request",
			"error":   err.Error(),
		}
		h.Ctx.Output.SetStatus(http.StatusBadRequest)
		return
	}
	beego.Debug("[C] Got data:", user)
	id, err := models.AddUser(user)
	if err != nil {
		beego.Warn("[C] Got error:", err)
		h.Data["json"] = map[string]string{
			"message": "Failed to add New host",
			"error":   err.Error(),
		}
		h.Ctx.Output.SetStatus(http.StatusInternalServerError)
		return
	}

	beego.Debug("[C] Got id:", id)
	h.Data["json"] = map[string]string{
		"id": id,
	}
	h.Ctx.Output.SetStatus(http.StatusCreated)
}
コード例 #2
0
// @Title createAppSet
// @router / [post]
func (a *AppSetsController) Post() {
	defer a.ServeJSON()
	appSet := new(models.AppSets)
	err := json.Unmarshal(a.Ctx.Input.RequestBody, appSet)
	if err != nil {
		beego.Warn("[C] Got error:", err)
		a.Data["json"] = map[string]string{
			"message": "Bad request",
			"error":   err.Error(),
		}
		a.Ctx.Output.SetStatus(http.StatusBadRequest)
		return
	}
	beego.Debug("[C] Got data:", appSet)
	id, err := models.AddAppSet(appSet)
	if err != nil {
		beego.Warn("[C] Got error:", err)
		a.Data["json"] = map[string]string{
			"message": "Failed to add New host",
			"error":   err.Error(),
		}
		a.Ctx.Output.SetStatus(http.StatusInternalServerError)
		return
	}

	beego.Debug("[C] Got id:", id)
	a.Data["json"] = map[string]string{
		"id": id,
	}
	a.Ctx.Output.SetStatus(http.StatusCreated)
	return
}
コード例 #3
0
// @Title createSignal
// @router /signal/:name [post]
func (c *ClientController) PostSignal() {
	name := c.GetString(":name")
	defer c.ServeJSON()
	beego.Debug("[C] Got name:", name)
	if name != "" {
		host := &models.Hosts{
			Name: name,
		}
		hosts, err := models.GetHosts(host, 0, 0)
		if err != nil {
			c.Data["json"] = map[string]string{
				"message": fmt.Sprint("Failed to get with name:", name),
				"error":   err.Error(),
			}
			beego.Warn("[C] Got error:", err)
			c.Ctx.Output.SetStatus(http.StatusInternalServerError)
			return
		}
		if len(hosts) == 0 {
			beego.Debug("[C] Got nothing with name:", name)
			c.Ctx.Output.SetStatus(http.StatusNotFound)
			return
		}
		var signal models.Signal
		err = json.Unmarshal(c.Ctx.Input.RequestBody, &signal)
		if err != nil {
			beego.Warn("[C] Got error:", err)
			c.Data["json"] = map[string]string{
				"message": "Bad request",
				"error":   err.Error(),
			}
			c.Ctx.Output.SetStatus(http.StatusBadRequest)
			return
		}
		beego.Debug("[C] Got data:", signal)
		id, err := models.AddSignal(hosts[0].Id, signal)
		if err != nil {
			beego.Warn("[C] Got error:", err)
			c.Data["json"] = map[string]string{
				"message": "Failed to add new signal",
				"error":   err.Error(),
			}
			c.Ctx.Output.SetStatus(http.StatusBadRequest)
			return
		}
		c.Data["json"] = map[string]string{
			"id": id,
		}
		c.Ctx.Output.SetStatus(http.StatusCreated)
	}
}
コード例 #4
0
// @Title updateAppSet
// @router /:name [put]
func (a *AppSetsController) Put() {
	name := a.GetString(":name")
	defer a.ServeJSON()
	beego.Debug("[C] Got appSet name:", name)
	if name != "" {
		appSet := &models.AppSets{
			Name: name,
		}
		appSets, err := models.GetAppSets(appSet, 0, 0)
		if err != nil {
			a.Data["json"] = map[string]string{
				"message": fmt.Sprint("Failed to get with name:", name),
				"error":   err.Error(),
			}
			beego.Warn("[C] Got error:", err)
			a.Ctx.Output.SetStatus(http.StatusInternalServerError)
			return
		}
		if len(appSets) == 0 {
			beego.Debug("[C] Got nothing with name:", name)
			a.Ctx.Output.SetStatus(http.StatusNotFound)
			return
		}

		err = json.Unmarshal(a.Ctx.Input.RequestBody, appSet)
		appSet.Id = appSets[0].Id
		if err != nil {
			beego.Warn("[C] Got error:", err)
			a.Data["json"] = map[string]string{
				"message": "Bad request",
				"error":   err.Error(),
			}
			a.Ctx.Output.SetStatus(http.StatusBadRequest)
			return
		}
		beego.Debug("[C] Got appSet data:", appSet)
		err = models.UpdateAppSet(appSet)
		if err != nil {
			a.Data["json"] = map[string]string{
				"message": fmt.Sprint("Failed to update with name:", name),
				"error":   err.Error(),
			}
			beego.Warn("[C] Got error:", err)
			a.Ctx.Output.SetStatus(http.StatusInternalServerError)
			return
		}
		a.Ctx.Output.SetStatus(http.StatusAccepted)
	}
}
コード例 #5
0
// @Title getUser
// @router /:name [get]
func (h *UserController) Get() {
	name := h.GetString(":name")
	beego.Debug("[C] Got name:", name)
	defer h.ServeJSON()
	if name != "" {
		user := &models.Users{
			Name: name,
		}
		users, err := models.GetUser(user, 0, 0)
		if err != nil {
			h.Data["json"] = map[string]string{
				"message": fmt.Sprint("Failed to get  with name:", name),
				"error":   err.Error(),
			}
			beego.Warn("[C] Got error:", err)
			h.Ctx.Output.SetStatus(http.StatusInternalServerError)
			return
		}
		h.Data["json"] = users
		if len(users) == 0 {
			beego.Debug("[C] Got nothing with name:", name)
			h.Ctx.Output.SetStatus(http.StatusNotFound)
		} else {
			h.Ctx.Output.SetStatus(http.StatusOK)
		}
	}
}
コード例 #6
0
ファイル: rawtrainrecord.go プロジェクト: Lkyzlwj/Graduate
/**
POST: collect train record data
body: json, two types, append and flush
{
  "op" : $op(append, flush)
  "player": $player
  "data": $data
}
result:
{
  "success": $succ
}
*/
func (this *RawTrainRecordController) Post() {
	type PostData struct {
		Op     string               `json:"op"`
		Player string               `json:"player"`
		Data   types.RawTrainRecord `json:"data"`
	}
	type Success struct {
		Succ bool `json:"success"`
	}

	var data PostData
	json.Unmarshal(this.Ctx.Input.RequestBody, &data)
	switch data.Op {
	case "append":
		models.AppendRawTrainData(data.Player, &data.Data)
		this.Data["json"] = &Success{true}
	case "flush":
		err := models.FlushRawTrainData()
		if err != nil {
			beego.Warn("Flush train data error, database error: ", err)
			this.Data["json"] = errors.Issue("Flush raw train data failed",
				errors.E_TYPE_SERVICE+errors.E_MODULE_TRAINRECORD+errors.E_DETAIL_INTERNAL_DB_ERROR,
				this.Ctx.Request.URL.String())
		} else {
			this.Data["json"] = &Success{true}
		}
	default:
		this.Data["json"] = errors.Issue("parameter op needed",
			errors.E_TYPE_SERVICE+errors.E_MODULE_TRAINRECORD+errors.E_DETAIL_ILLEGAL_PARAM,
			this.Ctx.Request.URL.String())
	}
	this.ServeJson()
}
コード例 #7
0
// @Title listAppSets
// @router / [get]
func (a *AppSetsController) GetAll() {
	limit, _ := a.GetInt("limit", 0)
	index, _ := a.GetInt("index", 0)

	defer a.ServeJSON()

	appSet := &models.AppSets{}
	appSets, err := models.GetAppSets(appSet, limit, index)
	if err != nil {
		a.Data["json"] = map[string]string{
			"message": fmt.Sprint("Failed to get"),
			"error":   err.Error(),
		}
		beego.Warn("[C] Got error:", err)
		a.Ctx.Output.SetStatus(http.StatusInternalServerError)
		return
	}
	a.Data["json"] = appSets
	if len(appSets) == 0 {
		beego.Debug("[C] Got nothing")
		a.Ctx.Output.SetStatus(http.StatusNotFound)
	} else {
		a.Ctx.Output.SetStatus(http.StatusOK)
	}
}
コード例 #8
0
// @Title getSignals
// @router /signal/:name [get]
func (c *ClientController) GetSignals() {
	name := c.GetString(":name")
	defer c.ServeJSON()
	beego.Debug("[C] Got name:", name)
	if name != "" {
		host := &models.Hosts{
			Name: name,
		}
		hosts, err := models.GetHosts(host, 0, 0)
		if err != nil {
			c.Data["json"] = map[string]string{
				"message": fmt.Sprint("Failed to get with name:", name),
				"error":   err.Error(),
			}
			beego.Warn("[C] Got error:", err)
			c.Ctx.Output.SetStatus(http.StatusInternalServerError)
			return
		}
		if len(hosts) == 0 {
			beego.Debug("[C] Got nothing with name:", name)
			c.Ctx.Output.SetStatus(http.StatusNotFound)
			return
		}
		c.Data["json"] = models.GetSignals(hosts[0].Id)
		c.Ctx.Output.SetStatus(http.StatusOK)
	}
}
コード例 #9
0
// @Title getAppSet
// @router /:name [get]
func (a *AppSetsController) Get() {
	name := a.GetString(":name")
	defer a.ServeJSON()
	beego.Debug("[C] Got name:", name)
	if name != "" {
		appSet := &models.AppSets{
			Name: name,
		}
		appSets, err := models.GetAppSets(appSet, 0, 0)
		if err != nil {
			a.Data["json"] = map[string]string{
				"message": fmt.Sprint("Failed to get  with name:", name),
				"error":   err.Error(),
			}
			beego.Warn("[C] Got error:", err)
			a.Ctx.Output.SetStatus(http.StatusInternalServerError)
			return
		}
		a.Data["json"] = appSets
		if len(appSets) == 0 {
			beego.Debug("[C] Got nothing with name:", name)
			a.Ctx.Output.SetStatus(http.StatusNotFound)
		} else {
			a.Ctx.Output.SetStatus(http.StatusOK)
		}
	}
}
コード例 #10
0
ファイル: trainhistory.go プロジェクト: Lkyzlwj/Graduate
/**
GET: request the history train data(processed remark)
params: player=$player&page=$page&num=$num
result:
{
	"result": [{}, {}, ...],
	"total_number": 2,
  "before": 0,
  "current": 1,
  "next": 0
}
*/
func (this *TrainHistoryController) Get() {
	page, err := this.GetInt("page", 0)
	if err != nil {
		beego.Warn("Query train history error, parse page error: ", err)
		this.Data["json"] = errors.Issue("Parse page error",
			errors.E_TYPE_SERVICE+errors.E_MODULE_TRAINHISTORY+errors.E_DETAIL_PARSE_PARAM_ERROR,
			this.Ctx.Request.URL.String())
		this.ServeJson()
		return
	}

	num, err := this.GetInt("num", 10)
	if err != nil {
		beego.Warn("Query train history error, parse num error: ", err)
		this.Data["json"] = errors.Issue("Parse num error",
			errors.E_TYPE_SERVICE+errors.E_MODULE_TRAINHISTORY+errors.E_DETAIL_PARSE_PARAM_ERROR,
			this.Ctx.Request.URL.String())
		this.ServeJson()
		return
	}

	if page < 0 || num < 0 {
		beego.Warn("Query train history error, wrong params: page, num = ", page, num)
		this.Data["json"] = errors.Issue("Page and num must be non-negative",
			errors.E_TYPE_SERVICE+errors.E_MODULE_TRAINHISTORY+errors.E_DETAIL_ILLEGAL_PARAM,
			this.Ctx.Request.URL.String())
		this.ServeJson()
		return
	}

	player := this.GetString("player")
	if len(player) != 40 {
		beego.Warn("Query train history error, wrong params: player = ", player)
		this.Data["json"] = errors.Issue("Invalid player",
			errors.E_TYPE_SERVICE+errors.E_MODULE_TRAINHISTORY+errors.E_DETAIL_ILLEGAL_PARAM,
			this.Ctx.Request.URL.String())
		this.ServeJson()
		return
	}

	this.Data["json"] = models.QueryTrainRecord(player, page, num)

	beego.Info(fmt.Sprintf("Query train history, req: %s, player: %s, page: %d, num: %d",
		this.Ctx.Request.URL.String(), player, page, num))

	this.ServeJson()
}
コード例 #11
0
ファイル: appsMonitor.go プロジェクト: souche-open/smoni
func (mapp *MonitorForApp) check_once() bool {
	milliseconds := 500
	client := &http.Client{
		Timeout: time.Duration(milliseconds) * time.Millisecond,
	}
	resp, err := client.Get(mapp.Url)
	if err != nil {
		beego.Warn("check app error : " + err.Error())
		return false
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		beego.Warn("check app status is : " + strconv.Itoa(resp.StatusCode))
		return false
	}
	return true
}
コード例 #12
0
ファイル: crit.go プロジェクト: grr89/hrkb
// show all criteria
func (c *Crit) Index() {
	crit := &M.Crit{}
	groups, err := crit.GetGroupedCrits()
	if err != nil {
		beego.Warn("GroupError", err)
	}
	c.Data["groups"] = groups
}
コード例 #13
0
ファイル: http.go プロジェクト: kobeyyf/beeweb
func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
	timer := time.AfterFunc(*requestTimeout, func() {
		t.t.CancelRequest(req)
		beego.Warn("Canceled request for %s", req.URL)
	})
	defer timer.Stop()
	resp, err := t.t.RoundTrip(req)
	return resp, err
}
コード例 #14
0
ファイル: rat.go プロジェクト: grr89/hrkb
// save concrete candidate rating
func (c *Rat) Post() {

	if !c.IsAjax() {
		return
	}

	var err error
	var s string
	var v M.ValidMap
	var ok bool

	r := M.Rat{Active: true}

	err = c.ParseForm(&r)

	uid := c.GetSession("uid")
	if uid == nil {
		c.Data["json"] = RJson{T("auth_is_off"), ok}
		return
	}

	fr := M.Rat{}
	err = DM.Find(&fr, M.Sf{}, M.Where{And: M.W{"Cand": r.Cand, "User": uid.(int), "Crit": r.Crit}})
	if err != nil && err != sql.ErrNoRows {
		c.Data["json"] = RJson{T("internal"), ok}
		beego.Warn(err)
		return
	}

	if fr.Id > 0 {
		c.Data["json"] = RJson{T("rat_already"), ok}
		return
	}

	r.User = uid.(int)

	if err == sql.ErrNoRows {
		v, err = DM.Insert(&r)
	}

	if err != nil {
		s = T("save_error")
		beego.Error(err)
	}

	if !v.HasErrors() {
		s = T("rat_added")
		ok = true
	} else {
		s = T("validation_error")
	}

	c.Data["json"] = RJson{s, ok}
}
コード例 #15
0
ファイル: db.go プロジェクト: yearnfar/gocms
func (d *Db) M(collection string, f func(*mgo.Collection)) {
	session := d.Dial()
	defer func() {
		session.Close()
		if err := recover(); err != nil {
			beego.Warn(fmt.Sprintf("MongoDB recover: %s", err))
		}
	}()
	c := session.DB(beego.AppConfig.String("MONGO_DbName")).C(collection)
	f(c)
}
コード例 #16
0
ファイル: wblog.go プロジェクト: zixinjian/webo_dev
func LogItemDelete(item interface{}, deleter string) bool {
	log := logs.NewLogger(10000)
	log.SetLogger("file", `{"filename":"db/deletedItems.log"}`)
	if b, err := json.Marshal(item); err == nil {
		fmt.Println(b)
		beego.Warn("deleter: ", deleter, " item: ", string(b))
		log.Info("deleter: ", deleter, " item: ", string(b))
		return true
	}
	return false
}
コード例 #17
0
ファイル: trainremark.go プロジェクト: Lkyzlwj/Graduate
/**
GET: request the processed remark
params: player=$player&page=$page&num=$num
result:
{
	"result": [...],
	"total_number": 2,
  "before": 0,
  "current": 1,
  "next": 0
}
*/
func (this *TrainRemarkController) Get() {
	player := this.GetString("player")
	if len(player) != 40 {
		beego.Warn("Query train remark error, wrong params: player = ", player)
		this.Data["json"] = errors.Issue("Invalid player",
			errors.E_TYPE_SERVICE+errors.E_MODULE_TRAINREMARK+errors.E_DETAIL_ILLEGAL_PARAM,
			this.Ctx.Request.URL.String())
		this.ServeJson()
		return
	}

	page, err := this.GetInt("page", 0)
	if err != nil {
		beego.Warn("Get players error, parse page error: ", err)
		this.Data["json"] = errors.Issue("Parse page error",
			errors.E_TYPE_SERVICE+errors.E_MODULE_TRAINREMARK+errors.E_DETAIL_PARSE_PARAM_ERROR,
			this.Ctx.Request.URL.String())
		this.ServeJson()
		return
	}

	num, err := this.GetInt("num", 10)
	if err != nil {
		beego.Warn("Get players error, parse num error: ", err)
		this.Data["json"] = errors.Issue("Parse num error",
			errors.E_TYPE_SERVICE+errors.E_MODULE_TRAINREMARK+errors.E_DETAIL_PARSE_PARAM_ERROR,
			this.Ctx.Request.URL.String())
		this.ServeJson()
		return
	}

	this.Data["json"] = models.GetTrainRecord(player, page, num)
	beego.Info(fmt.Sprintf("Query train remark, req: %s, player: %s, page: %d, num: %d",
		this.Ctx.Request.URL.String(), player, page, num))

	this.ServeJson()
}
コード例 #18
0
ファイル: players.go プロジェクト: Lkyzlwj/Graduate
/**
GET: query players
params: page, num
result: json
error happened:
{
	"error": "Error message",
	"error_code": $code,
	"request": "/api/player?page=$page&num=$num"
}
success:
{
	"result": [{}, {}, ...],
	"total_number": 2,
  "before": 0,
  "current": 1,
  "next": 0
}
*/
func (this *PlayersController) Get() {
	page, err := this.GetInt("page", 0)
	if err != nil {
		beego.Warn("Get players error, parse page error: ", err)
		this.Data["json"] = errors.Issue("Parse page error",
			errors.E_TYPE_SERVICE+errors.E_MODULE_PLAYER+errors.E_DETAIL_PARSE_PARAM_ERROR,
			this.Ctx.Request.URL.String())
		this.ServeJson()
		return
	}

	num, err := this.GetInt("num", 10)
	if err != nil {
		beego.Warn("Get players error, parse num error: ", err)
		this.Data["json"] = errors.Issue("Parse num error",
			errors.E_TYPE_SERVICE+errors.E_MODULE_PLAYER+errors.E_DETAIL_PARSE_PARAM_ERROR,
			this.Ctx.Request.URL.String())
		this.ServeJson()
		return
	}

	if page < 0 || num < 0 {
		beego.Warn("Get players error, wrong params: page, num = ", page, num)
		this.Data["json"] = errors.Issue("Page and num must be non-negative",
			errors.E_TYPE_SERVICE+errors.E_MODULE_PLAYER+errors.E_DETAIL_ILLEGAL_PARAM,
			this.Ctx.Request.URL.String())
		this.ServeJson()
		return
	}

	beego.Info(fmt.Sprintf("Query player, req: %s, page: %d, num: %d",
		this.Ctx.Request.URL.String(), page, num))

	this.Data["json"] = models.QueryPlayer(page, num)
	this.ServeJson()
}
コード例 #19
0
ファイル: default.go プロジェクト: finove/fileserver
func (this *MainController2) Post() {
	var filename = this.Ctx.Input.Param(":filename")
	if this.Ctx.Input.RequestBody == nil {
		this.Ctx.Input.CopyBody()
	}
	fout, err := os.Create("files/" + filename)
	defer fout.Close()
	if err != nil {
		beego.Warn("create file", filename, "fail")
	} else {
		fout.Write(this.Ctx.Input.RequestBody)
	}
	this.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	this.Ctx.Output.SetStatus(200)
}
コード例 #20
0
ファイル: server.go プロジェクト: weixinhost/beego-yar
func (self *Server) Handle() (bool, error) {

	self.body = self.ctx.Input.RequestBody

	var err error

	if len(self.body) < (PROTOCOL_LENGTH + PACKAGER_LENGTH) {

		return false, errors.New("read request body error.")
	}

	header, err := self.getHeader()

	if err != nil {
		beego.Error(err)
		return false, err
	}

	request, err := self.getRequest(header)

	if err != nil {
		beego.Error(err)
		return false, err
	}

	response := NewResponse()
	response.Status = ERR_OKEY
	response.Protocol = header
	self.call(request, response)
	self.sendResponse(response)

	if response.Status != ERR_OKEY {

		beego.Warn(request.Id, request.Method, response.Error)

	} else {

		beego.Notice(request.Id, request.Method, "OKEY")

	}

	return true, nil
}
コード例 #21
0
ファイル: storage.go プロジェクト: Lkyzlwj/Graduate
func init() {
	//open db
	//the access of db needn't sync, it's done by mongo
	var err error
	dbHelper, err = dbhelper.Open(dbHost, dbName, playersCollName)
	if err != nil {
		panic(err)
	}

	//preload all players
	players, err = dbHelper.QueryAllPlayer()
	if err != nil {
		if players == nil {
			panic(err)
		} //else
		beego.Warn("Error happened when query all player: ", err)
	}

	if players == nil {
		players = make([]types.Player, 0)
	}

	//auth
	appConf, err := config.NewConfig("ini", "conf/app.conf")
	if err != nil {
		panic(err)
	}

	username = appConf.String("admin::username")
	password = appConf.String("admin::password")
	rander = rand.New(rand.NewSource(time.Now().UnixNano()))
	ResetToken()

	//these two maps should sync, ideally it needn't, cause every device access
	//its own k-v pair. but it can not be guaranteed
	//raw train record
	rawTrainRecord = make(map[string]types.RawTrainRecord)
	//processed record
	processedRecord = make(map[string]types.TrainRecord)
	//raw train record processor
	rawDataProcessor = processor.NaiveProcessor{}
}
コード例 #22
0
ファイル: main.go プロジェクト: grr89/hrkb
//check auth form
func (c *Main) Post() {

	var v M.ValidMap

	c.Data["xsrfdata"] = template.HTML(c.XsrfFormHtml())
	c.TplNames = "loginform.tpl"

	loginform := LoginForm{}
	c.ParseForm(&loginform)
	v.Valid(loginform)

	c.Data["login"] = loginform.Login
	M.ExpandFormErrors(&v, c.Data)

	if v.HasErrors() {
		return
	}

	c.Data["errLogin"] = T("login_error")
	id, err := M.CheckPass(loginform.Login, loginform.Password)

	if err != nil {
		beego.Warn(err)
		return
	}

	u := M.User{}
	err = DM.FindByPk(&u, id)
	if err != nil {
		beego.Error(err)
		return
	}

	if len(u.GToken.String) > 0 {
		c.SetSession("gitlabToken", u.GToken.String)
	}
	c.SetSession("uid", id)
	c.SetSession("role", u.Role)
	c.SetSession("name", u.Name)
	c.Redirect(beego.UrlFor("Cand.Index"), 302)
}
コード例 #23
0
ファイル: init.go プロジェクト: cluo/webcron
func runCmdWithTimeout(cmd *exec.Cmd, timeout time.Duration) (error, bool) {
	done := make(chan error)
	go func() {
		done <- cmd.Wait()
	}()

	var err error
	select {
	case <-time.After(timeout):
		beego.Warn(fmt.Sprintf("任务执行时间超过%d秒,进程将被强制杀掉: %d", int(timeout/time.Second), cmd.Process.Pid))
		go func() {
			<-done // 读出上面的goroutine数据,避免阻塞导致无法退出
		}()
		if err = cmd.Process.Kill(); err != nil {
			beego.Error(fmt.Sprintf("进程无法杀掉: %d, 错误信息: %s", cmd.Process.Pid, err))
		}
		return err, true
	case err = <-done:
		return err, false
	}
}
コード例 #24
0
ファイル: gorelic.go プロジェクト: jiaxinwang/beego_gorelic
func InitNewrelicAgent() {

	license := beego.AppConfig.String("NewrelicLicense")
	if license == "" {
		beego.Warn("Please specify NewRelic license in the application config: NewrelicLicense=7bceac019c7dcafae1ef95be3e3a3ff8866de245")
		return
	}

	agent = gorelic.NewAgent()
	agent.NewrelicLicense = license

	agent.HTTPTimer = metrics.NewTimer()
	agent.CollectHTTPStat = true

	if beego.RunMode == "dev" {
		agent.Verbose = true
	}
	if verbose, err := beego.AppConfig.Bool("NewrelicVerbose"); err == nil {
		agent.Verbose = verbose
	}

	nameParts := []string{beego.AppConfig.String("appname")}
	switch strings.ToLower(beego.AppConfig.String("NewrelicAppnameRunmode")) {
	case "append":
		nameParts = append(nameParts, beego.RunMode)

	case "prepend":
		nameParts = append([]string{beego.RunMode}, nameParts...)
	}
	agent.NewrelicName = strings.Join(nameParts, SEPARATOR)
	agent.Run()

	beego.InsertFilter("*", beego.BeforeRouter, InitNewRelicTimer, false)
	beego.InsertFilter("*", beego.FinishRouter, ReportMetricsToNewrelic, false)

	beego.Info("NewRelic agent started")
}
コード例 #25
0
ファイル: players.go プロジェクト: Lkyzlwj/Graduate
/**
POST: insert or update player(ObjId not empty means update)
request body: player info(json)
result: json
success:
{
	"success": true,
	"id": $ObjId
}
*/
func (this *PlayersController) Post() {
	var player types.Player
	json.Unmarshal(this.Ctx.Input.RequestBody, &player)
	/*if !player.Valid() {
		beego.Warn("Add/Update players error, invalid data: ", player, string(this.Ctx.Input.RequestBody))
		this.Data["json"] = errors.Issue("Player info incomplete",
			errors.E_TYPE_SERVICE + errors.E_MODULE_PLAYER + errors.E_DETAIL_INCOMPLETE_DATA,
			this.Ctx.Request.URL.String())
		this.ServeJson()
		return
	}*/
	beego.Info("data & player ", string(this.Ctx.Input.RequestBody), player)
	var err error
	if player.ObjId != "" {
		err = models.UpdatePlayer(&player)
	} else {
		err = models.InsertPlayer(&player)
	}

	if err != nil {
		beego.Warn("Add/Update players error, database error: ", err)
		this.Data["json"] = errors.Issue("Database operate error",
			errors.E_TYPE_SERVICE+errors.E_MODULE_PLAYER+errors.E_DETAIL_INTERNAL_DB_ERROR,
			this.Ctx.Request.URL.String())
		this.ServeJson()
		return
	}

	beego.Info("Add/Update players success, player id: ", player.ObjId.Hex())

	type Success struct {
		Succ         bool `json:"success"`
		types.Player `json:"player"`
	}
	this.Data["json"] = &Success{true, player}
	this.ServeJson()
}
コード例 #26
0
// @Title listUser
// @router / [get]
func (h *UserController) GetAll() {
	limit, _ := h.GetInt("limit", 0)
	index, _ := h.GetInt("index", 0)

	defer h.ServeJSON()
	user := &models.Users{}
	users, err := models.GetUser(user, limit, index)
	if err != nil {
		h.Data["json"] = map[string]string{
			"message": fmt.Sprint("Failed to get"),
			"error":   err.Error(),
		}
		beego.Warn("[C] Got error:", err)
		h.Ctx.Output.SetStatus(http.StatusInternalServerError)
		return
	}
	h.Data["json"] = users
	if len(users) == 0 {
		beego.Debug("[C] Got nothing")
		h.Ctx.Output.SetStatus(http.StatusNotFound)
	} else {
		h.Ctx.Output.SetStatus(http.StatusOK)
	}
}
コード例 #27
0
// @Title updateUser
// @router /:name [put]
func (h *UserController) Put() {
	name := h.GetString(":name")
	defer h.ServeJSON()
	beego.Debug("[C] Got user name:", name)
	if name != "" {
		user := &models.Users{
			Name: name,
		}
		users, err := models.GetUser(user, 0, 0)
		if err != nil {
			h.Data["json"] = map[string]string{
				"message": fmt.Sprint("Failed to get with name:", name),
				"error":   err.Error(),
			}
			beego.Warn("[C] Got error:", err)
			h.Ctx.Output.SetStatus(http.StatusInternalServerError)
			return
		}
		if len(users) == 0 {
			beego.Debug("[C] Got nothing with name:", name)
			h.Ctx.Output.SetStatus(http.StatusNotFound)
			return
		}

		sessionId := h.GetSession("id")
		if sessionId != nil {
			userNow := &models.Users{
				Id: sessionId.(string),
			}
			userNows, err := models.GetUser(userNow, 0, 0)
			if err != nil {
				h.Data["json"] = map[string]string{
					"message": fmt.Sprint("Failed to get with name:", name),
					"error":   err.Error(),
				}
				beego.Warn("[C] Got error:", err)
				h.Ctx.Output.SetStatus(http.StatusInternalServerError)
				return
			}
			if len(userNows) == 0 {
				beego.Debug("[C] Invalid user id:", sessionId)
				h.Ctx.Output.SetStatus(http.StatusNotFound)
				return
			}
		}

		err = json.Unmarshal(h.Ctx.Input.RequestBody, user)
		if err != nil {
			beego.Warn("[C] Got error:", err)
			h.Data["json"] = map[string]string{
				"message": "Bad request",
				"error":   err.Error(),
			}
			h.Ctx.Output.SetStatus(http.StatusBadRequest)
			return
		}
		user.Id = users[0].Id
		user.Removable = users[0].Removable // Removable should not be changed.
		if user.Password != users[0].Password {
			user.Password = common.EncryptPassword(user.Password)
		}
		beego.Debug("[C] Got user data:", user)
		err = models.UpdateUser(user)
		if err != nil {
			h.Data["json"] = map[string]string{
				"message": fmt.Sprint("Failed to update with name:", name),
				"error":   err.Error(),
			}
			beego.Warn("[C] Got error:", err)
			h.Ctx.Output.SetStatus(http.StatusInternalServerError)
			return
		}
		h.Ctx.Output.SetStatus(http.StatusAccepted)
	}
}
コード例 #28
0
ファイル: home.go プロジェクト: JoeyFan/gowalker
// Get implemented Get method for HomeRouter.
func (this *HomeRouter) Get() {
	// Filter unusual User-Agent.
	ua := this.Ctx.Request.Header.Get("User-Agent")
	if len(ua) < 20 {
		beego.Warn("User-Agent:", this.Ctx.Request.Header.Get("User-Agent"))
		this.Ctx.WriteString("")
		return
	}

	// Set language version.
	curLang := globalSetting(this.Ctx, this.Input(), this.Data)

	// Get argument(s).
	q := strings.TrimRight(
		strings.TrimSpace(this.Input().Get("q")), "/")

	if path, ok := utils.IsBrowseURL(q); ok {
		q = path
	}

	// Get pure URL.
	reqUrl := this.Ctx.Request.RequestURI[1:]
	if i := strings.Index(reqUrl, "?"); i > -1 {
		reqUrl = reqUrl[:i]
		if path, ok := utils.IsBrowseURL(reqUrl); ok {
			reqUrl = path
		}
	}

	// Redirect to query string.
	if len(reqUrl) == 0 && len(q) > 0 {
		reqUrl = q
		this.Redirect("/"+reqUrl, 302)
		return
	}

	// User Recent projects.
	urpids, _ := this.Ctx.Request.Cookie("UserRecentPros")
	urpts, _ := this.Ctx.Request.Cookie("URPTimestamps")

	this.TplNames = "home_" + curLang.Lang + ".html"
	// Check to show home page or documentation page.
	if len(reqUrl) == 0 && len(q) == 0 {
		serveHome(this, urpids, urpts)
	} else {
		// Documentation.
		this.TplNames = "docs_" + curLang.Lang + ".html"
		broPath := reqUrl // Browse path.

		// Check if it's the standard library.
		if utils.IsGoRepoPath(broPath) {
			broPath = "code.google.com/p/go/source/browse/src/pkg/" + broPath
		}

		// Check if it's a remote path that can be used for 'go get', if not means it's a keyword.
		if !utils.IsValidRemotePath(broPath) {
			// Search.
			this.Redirect("/search?q="+reqUrl, 302)
			return
		}

		// Get tag field.
		tag := strings.TrimSpace(this.Input().Get("tag"))
		if tag == "master" || tag == "default" {
			tag = ""
		}

		// Check documentation of this import path, and update automatically as needed.
		pdoc, err := doc.CheckDoc(reqUrl, tag, doc.HUMAN_REQUEST)
		if err == nil {
			if pdoc != nil {
				pdoc.UserExamples = getUserExamples(pdoc.ImportPath)
				// Generate documentation page.
				if generatePage(this, pdoc, broPath, tag, curLang.Lang) {
					ps, ts := updateCacheInfo(pdoc, urpids, urpts)
					this.Ctx.SetCookie("UserRecentPros", ps, 9999999999, "/")
					this.Ctx.SetCookie("URPTimestamps", ts, 9999999999, "/")
					return
				}
			}
		} else {
			this.Data["IsHasError"] = true
			this.Data["ErrMsg"] = strings.Replace(err.Error(),
				doc.GetGithubCredentials(), "<githubCred>", 1)
			beego.Error("HomeRouter.Get ->", err)
			this.TplNames = "home_" + curLang.Lang + ".html"
			serveHome(this, urpids, urpts)
			return
		}

		this.Redirect("/search?q="+reqUrl, 302)
		return
	}
}
コード例 #29
0
ファイル: log.go プロジェクト: e-wings/go-tools
func Warn(message string) {
	beego.Warn(message)
	Log.logger.Warn(message)
}
コード例 #30
0
ファイル: home.go プロジェクト: seacoastboy/gowalker
// Get implemented Get method for HomeRouter.
func (this *HomeRouter) Get() {
	// Filter unusual User-Agent.
	ua := this.Ctx.Request.Header.Get("User-Agent")
	if len(ua) < 20 {
		beego.Warn("User-Agent:", this.Ctx.Request.Header.Get("User-Agent"))
		return
	}

	// Set language version.
	curLang := setLangVer(this.Ctx, this.Input(), this.Data)

	// Get query field.
	q := strings.TrimSpace(this.Input().Get("q"))

	// Remove last "/".
	q = strings.TrimRight(q, "/")

	if path, ok := utils.IsBrowseURL(q); ok {
		q = path
	}

	// Get pure URL.
	reqUrl := this.Ctx.Request.RequestURI[1:]
	if i := strings.Index(reqUrl, "?"); i > -1 {
		reqUrl = reqUrl[:i]
		if path, ok := utils.IsBrowseURL(reqUrl); ok {
			reqUrl = path
		}
	}

	// Redirect to query string.
	if len(reqUrl) == 0 && len(q) > 0 {
		reqUrl = q
		this.Redirect("/"+reqUrl, 302)
		return
	}

	// Check show home page or documentation page.
	if len(reqUrl) == 0 && len(q) == 0 {
		// Home page.
		this.Data["IsHome"] = true
		this.TplNames = "home_" + curLang.Lang + ".html"

		// Recent projects
		this.Data["RecentPros"] = recentViewedPros
		// Get popular project and examples list from database.
		this.Data["PopPros"], this.Data["RecentExams"] = models.GetPopulars(20, 12)
		// Set standard library keyword type-ahead.
		this.Data["DataSrc"] = utils.GoRepoSet
	} else {
		// Documentation page.
		this.TplNames = "docs_" + curLang.Lang + ".html"
		broPath := reqUrl // Browse path.

		// Check if it is standard library.
		if utils.IsGoRepoPath(broPath) {
			broPath = "code.google.com/p/go/source/browse/src/pkg/" + broPath
		}

		// Check if it is a remote path that can be used for 'gopm get', if not means it's a keyword.
		if !utils.IsValidRemotePath(broPath) {
			// Show search page
			this.Redirect("/search?q="+reqUrl, 302)
			return
		}

		// Get tag field.
		tag := strings.TrimSpace(this.Input().Get("tag"))
		if tag == "master" || tag == "default" {
			tag = ""
		}

		// Check documentation of this import path, and update automatically as needed.
		pdoc, err := doc.CheckDoc(reqUrl, tag, doc.HUMAN_REQUEST)
		if err == nil || pdoc == nil {
			pdoc.UserExamples = getUserExamples(pdoc.ImportPath)
			// Generate documentation page.
			if generatePage(this, pdoc, broPath, tag, curLang.Lang) {
				// Update recent project list.
				updateRecentPros(pdoc)
				// Update project views.
				pinfo := &models.PkgInfo{
					Path:        pdoc.ImportPath,
					Synopsis:    pdoc.Synopsis,
					Created:     pdoc.Created,
					ProName:     pdoc.ProjectName,
					ViewedTime:  pdoc.ViewedTime,
					Views:       pdoc.Views,
					IsCmd:       pdoc.IsCmd,
					Etag:        pdoc.Etag,
					Labels:      pdoc.Labels,
					Tags:        strings.Join(pdoc.Tags, "|||"),
					ImportedNum: pdoc.ImportedNum,
					ImportPid:   pdoc.ImportPid,
				}
				models.AddViews(pinfo)
				return
			}
		} else {
			beego.Error("HomeRouter.Get ->", err)
		}

		// Show search page
		this.Redirect("/search?q="+reqUrl, 302)
		return
	}
}