본문 바로가기
Go

[Go] RESTFul API 구현

by 혀나Lee 2016. 9. 22.

주제

1. https://gin-gonic.github.io/gin/

2. http://jinzhu.me/gorm/

3. gorm, gin-gonic을 이용하여 실제 RESTFul API를 구현


$ go get github.com/jinzhu/gorm

$ go get github.com/gin-gonic/gin


과제

CREATE SEQUENCE seq_user

INCREMENT 1

MINVALUE 1

MAXVALUE 9223372036854775807

START 1

CACHE 1;


CREATE TABLE "user"

(

user_seq_no bigint NOT NULL DEFAULT nextval('seq_user'::regclass), 

name character varying(10) NOT NULL,

email character varying(30) NOT NULL,

age smallint NOT NULL,

birthday date NOT NULL,

mobile character varying(20) NOT NULL,

insert_datetime timestamp without time zone NOT NULL,

CONSTRAINT pk_user PRIMARY KEY (user_seq_no)

)

WITH (

OIDS=FALSE

);


COMMENT ON COLUMN user.user_seq_no IS '시퀀스';

COMMENT ON COLUMN user.name IS '회원 이름';

COMMENT ON COLUMN user.email IS '회원 이메일';

COMMENT ON COLUMN user.age IS '나이';

COMMENT ON COLUMN user.birthday IS '생년월일';

COMMENT ON COLUMN user.mobile IS '핸드폰 번호';

COMMENT ON COLUMN user.insert_datetime IS '등록일시';


코드

리팩토링을 하지 않은 코드이므로 감안하여 보길 바랍니다.

package main import ( _ "database/sql" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" "github.com/gin-gonic/gin" "log" "time" "net/http" "strconv" "fmt" ) type User struct { // 컬럼명은 대문자여야 한다 User_seq_no uint64 `gorm:"primary_key"` Name string Email string Age int Birthday string Mobile string Insert_datetime time.Time // time.Time import "time" } func (User) TableName() string { // set table name return "t_user" } func main() { // set api router router := gin.Default() router.GET("/users", get_users) router.POST("/users", post_users) router.PUT("/users/:pk", put_users) router.DELETE("/users/:pk", delete_users) router.Run(":8000") } func get_users (c *gin.Context) { // set database db, err := gorm.Open("postgres", "user=_user_ password=_password_ dbname=golang sslmode=disable") if err != nil { log.Fatal("faild to connect database") } defer db.Close() // get users var users []User db.Find(&users) c.JSON(http.StatusOK, gin.H{ "status": http.StatusOK, "data": &users, "message": nil, }) } func post_users(c *gin.Context) { // set database db, err := gorm.Open("postgres", "user=_user_ password=_password_ dbname=golang sslmode=disable") if err != nil { log.Fatal("faild to connect database") } defer db.Close() name := c.PostForm("name") email := c.PostForm("email") age, _ := strconv.Atoi(c.PostForm("age")) birthday := c.PostForm("birthday") mobile := c.PostForm("mobile") if name == "" || email == "" || age == 0 || mobile == "" { c.JSON(http.StatusBadRequest, gin.H{ "status": http.StatusBadRequest, "data": nil, "message": "Parameter is not valid.", }) } else { user := User{ Name: name, Email: email, Age: age, Birthday: birthday, Mobile: mobile, Insert_datetime: time.Now(), } if err := db.Create(&user).Error; err != nil { fmt.Print(err) c.JSON(http.StatusBadRequest, gin.H{ "status": http.StatusBadRequest, "data": nil, "message": err, }) } else { // 마지막 값을 가져와 반환한다 db.Last(&user) c.JSON(http.StatusOK, gin.H{ "status": http.StatusOK, "data": user, "message": nil, }) } } } func put_users (c *gin.Context) { // set database db, err := gorm.Open("postgres", "user=_user_ password=_password_ dbname=golang sslmode=disable") if err != nil { log.Fatal("faild to connect database") } defer db.Close() pk, _ := strconv.ParseUint(c.Param("pk"), 10, 32) name := c.PostForm("name") email := c.PostForm("email") age, _ := strconv.Atoi(c.PostForm("age")) birthday := c.PostForm("birthday") mobile := c.PostForm("mobile") user := User{ Name: name, Email: email, Age: age, Birthday: birthday, Mobile: mobile, } if err := db.Where(User{User_seq_no: pk}).Assign(user).FirstOrCreate(&user).Error; err != nil { fmt.Print(err) c.JSON(http.StatusBadRequest, gin.H{ "status": http.StatusBadRequest, "data": nil, "message": err, }) } else { c.JSON(http.StatusOK, gin.H{ "status": http.StatusOK, "data": user, "message": nil, }) } } func delete_users (c *gin.Context) { // set database db, err := gorm.Open("postgres", "user=_user_ password=_password_ dbname=golang sslmode=disable") if err != nil { log.Fatal("faild to connect database") } defer db.Close() pk, _ := strconv.ParseUint(c.Param("pk"), 10, 32) db.Where("user_seq_no = ?", pk).Delete(&User{}) c.JSON(http.StatusOK, gin.H{ "status": http.StatusOK, "data": nil, "message": "Delete Success.", }) }


댓글