コード例 #1
0
//curl localhost:9090/sshKeys -X POST -i -d '{"uid":4444444,"keyname":"testliuyanglong","publickey":"dasd"}''
func (this *SshKeysController) Post() {
	var sshKeysOb models.SshKeys
	requestBody := string(this.Ctx.Input.RequestBody)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &sshKeysOb)
	if err != nil {
		this.Ctx.Output.SetStatus(403)
		this.Ctx.Output.Body([]byte(`{"result":1,"error":"param error"}`))
		this.StopRun()
	}

	logid, err := models.GetLogId(this.Ctx.Input.RequestBody)
	if err != nil {
		this.Ctx.Output.SetStatus(403)
		this.Ctx.Output.Body([]byte(`{"result":1,"error":"logid param error"}`))
		this.StopRun()
	}
	logs.Normal("post data:", requestBody, "logid:", logid)
	dbconn, err := models.InitDbConn(logid)
	if err != nil {
		logs.Error("init db conn error!", err, "logid:", logid)
		this.Ctx.Output.SetStatus(500)
		this.Ctx.Output.Body([]byte(`{"result":1,"error":"init db conn error"}`))
		this.StopRun()
	}
	defer dbconn.Close()

	dbconn.Exec("START TRANSACTION")
	logs.Normal("start transaction", "logid:", logid)
	sshKeysM := new(models.SshKeysManage)
	err = sshKeysM.Insert(dbconn, sshKeysOb, logid)
	if err != nil {
		logs.Error("sshKeysM.Insert error!", err, "logid:", logid)
		dbconn.Exec("ROLLBACK")
		logs.Normal("ROLLBACK", "logid:", logid)
		this.Ctx.Output.SetStatus(500)
		this.Ctx.Output.Body([]byte(`{"result":1,"error":` + err.Error() + `}`))
		this.StopRun()
	}

	//reload ssh public key
	err = this.reloadSshPublicKeys(dbconn, strconv.Itoa(sshKeysOb.Uid), logid)
	if err != nil {
		logs.Error("reloadSshPublicKeys error!", err, sshKeysOb, "logid:", logid)
		dbconn.Exec("ROLLBACK")
		logs.Normal("ROLLBACK", "logid:", logid)
		this.Ctx.Output.SetStatus(500)
		this.Ctx.Output.Body([]byte(`{"result":1,"error":` + err.Error() + `}`))
		this.StopRun()
	}
	dbconn.Exec("COMMIT")
	logs.Normal("COMMIT", "logid:", logid)
	logs.Normal("post OK!", requestBody)
	this.Ctx.Output.Body([]byte(`{"result":0}`))
}