Exemple #1
0
func newPost(c *gin.Context) *Error {
	var post model.Post
	err := c.Bind(&post)
	if err != nil {
		return NewError(http.StatusBadRequest, "Bad Request", &err)
	}

	log.Printf("Post : %v\n", post)

	var user *model.User
	if post.SessionId != "" {
		user = GetUserBySessionId(post.SessionId)
	}
	if user == nil {
		user = &model.User{UserName: post.UserName}
	}
	if !user.IsValidUserName() {
		return NewError(http.StatusBadRequest, "user_name is not valid.", nil)
	}

	post.UserId = user.Id
	post.UserName = user.UserName

	log.Printf("Post (got user) : %v\n", post)

	// 他の書き込みを待機
	writeSemaphore <- 0
	defer func() { <-writeSemaphore }()

	err = database.WritePost(&post)
	if err != nil {
		return NewError(http.StatusInternalServerError, "Post can not be written.", &err)
	}

	c.JSON(http.StatusCreated, post.Id)

	return nil
}
Exemple #2
0
// ユーザーの登録を行います。
func (d *Database) WriteUser(user *model.User) error {
	tx, err := d.db.Begin()
	if err != nil {
		return err
	}

	if user.Id > 0 {
		// 更新
		stmt, err := tx.Prepare("update users set user_name=?, password_hash=? where id=?")
		if err != nil {
			return err
		}
		defer stmt.Close()

		_, err = stmt.Exec(user.UserName, user.PasswordHash, user.Id)
		if err != nil {
			return err
		}
	} else {
		// 新規
		stmt, err := tx.Prepare("insert into users (user_name, password_hash) values (?, ?)")
		if err != nil {
			return err
		}
		defer stmt.Close()

		res, err := stmt.Exec(user.UserName, user.PasswordHash)
		if err != nil {
			return err
		}

		id, err := res.LastInsertId()
		if err != nil {
			return err
		}
		user.Id = model.ID(id)
	}
	tx.Commit()

	return nil
}
Exemple #3
0
func newUser(c *gin.Context) *Error {
	var user model.User
	err := c.Bind(&user)
	if err != nil {
		return NewError(http.StatusBadRequest, "Bad Request", &err)
	}

	log.Printf("User : %v\n", user)

	if !user.IsValidUserName() {
		return NewError(http.StatusBadRequest, "user_name is not valid.", nil)
	}

	// ユーザーの存在チェック
	exist, err := database.IsUserNameExist(user.UserName)
	if err != nil {
		return NewError(http.StatusInternalServerError, "Can not read users.", &err)
	}
	if exist {
		return NewError(http.StatusConflict, "user_name is already exists.", nil)
	}

	if !user.CheckPassword() {
		return NewError(http.StatusBadRequest, "Password is not match.", nil)
	}

	user.SetPasswordHash()

	// 他の書き込みを待機
	writeSemaphore <- 0
	defer func() { <-writeSemaphore }()

	err = database.WriteUser(&user)
	if err != nil {
		return NewError(http.StatusInternalServerError, "User can not be written.", &err)
	}

	c.JSON(http.StatusCreated, user.Id)

	return nil
}