- postgresql 설치
- vscode 설치
- vscode에 postgresql 연동하기
- gin 프레임워크 사용, gorm 라이브러리 사용해서 개발
postgresql 설치 후 USER,DB,TABLE 생성
1. https://www.postgresql.org/
PostgreSQL
The world's most advanced open source database.
www.postgresql.org
2. 공식 홈페이지 들어가서 본인의 운영체제에 맞게 설치(자세한 방법은 아래 링크 참고! 잘 정리되어 있다.)
( https://backendcode.tistory.com/225 )
PostgreSQL 설치 및 세팅 & pgAdmin 사용법 - Windows
이번 글에서는 PostgreSQL 설치 방법과 초기 세팅, pgAdmin을 사용해 Database 생성 및 User 생성에 대해 정리할 것입니다. 우선 pgAdmin이란 PostgreSQL을 설치했을 때 기본적으로 설치되는 것이고, PostgreSQL을
backendcode.tistory.com
3. 터미널에서 $sudo -i -u postgres 로 접속 후, $psql 접속 하면 postgres=#으로 접속하게된다.
** pgadmin tool을 설치해서 사용해도 된다.
4. 이제 사용할 DB를 생성 -> create database test[생성할 DB이름];
5. 새로운 user 생성 -> create user testuser[생성할 user] with password '*****'[생성할 비밀번호];
5-1. superuser 권한을 부여한다.(필자 마음) -> alter user testuser[생성한 user] with superuser;
6. 만든 user의 db를 접속한다. -> psql -U testuser[생성한 계정] -d test[생성한 DB이름]
7. 그러면 아래처럼 접속된다. 그 후 테이블 생성
CREATE TABLE boards (
id SERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
writer VARCHAR(100) NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
);
Visual Studio Code 설치
1. https://code.visualstudio.com/
Visual Studio Code - Code Editing. Redefined
Visual Studio Code is a code editor redefined and optimized for building and debugging modern web and cloud applications. Visual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows.
code.visualstudio.com
간단한 CRUD 게시판 만들기
1. 서버와 연결 후, 폴더 가져오기
- myginiproject 디렉토리를 만든 후, 그 안에 main.go와 html을 만들었다.
2. main.go
package main
import (
"log"
"net/http"
"text/template"
"time"
"github.com/gin-gonic/gin"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
var db *gorm.DB
var tmpl = template.Must(template.ParseGlob("form/*"))
type board struct {
gorm.Model
Title string
Content string
Writer string
CreatedAt time.Time
}
func main() {
dsn := "host=localhost user=testuser password=1234 dbname=test sslmode=disable"
var err error
db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
db.AutoMigrate(&board{})
r := gin.Default()
r.GET("/api/v4/", Index)
r.GET("/api/v4/show/:id", Show)
r.GET("/api/v4/new", New)
r.GET("/api/v4/edit/:id", Edit)
r.POST("/api/v4/insert", Insert)
r.POST("/api/v4/update", Update)
r.GET("/api/v4/delete/:id", Delete)
r.Run(":3000")
}
func Index(c *gin.Context) {
var res []board
db.Find(&res)
tmpl.ExecuteTemplate(c.Writer, "Index", res)
}
func Show(c *gin.Context) {
id := c.Param("id")
var boardItem board
db.First(&boardItem, id)
tmpl.ExecuteTemplate(c.Writer, "Show", boardItem)
}
func New(c *gin.Context) {
tmpl.ExecuteTemplate(c.Writer, "New", nil)
}
func Edit(c *gin.Context) {
id := c.Param("id")
var boardItem board
db.First(&boardItem, id)
tmpl.ExecuteTemplate(c.Writer, "Edit", boardItem)
}
func Insert(c *gin.Context) {
if c.Request.Method == "POST" {
title := c.PostForm("title")
content := c.PostForm("content")
writer := c.PostForm("writer")
newBoard := board{
Title: title,
Content: content,
Writer: writer,
CreatedAt: time.Now(),
}
db.Create(&newBoard)
log.Println("INSERT: Title: " + title + " | Content: " + content + " | Writer: " + writer)
}
c.Redirect(http.StatusSeeOther, "/api/v4")
}
func Update(c *gin.Context) {
if c.Request.Method == "POST" {
id := c.PostForm("id")
title := c.PostForm("title")
content := c.PostForm("content")
writer := c.PostForm("writer")
var boardItem board
db.First(&boardItem, id)
boardItem.Title = title
boardItem.Content = content
boardItem.Writer = writer
result := db.Save(&boardItem)
log.Println(result.Error, result.RowsAffected)
log.Println("UPDATE: Title: " + title + " | Content: " + content + " | Writer: " + writer)
}
c.Redirect(http.StatusSeeOther, "/api/v4")
}
func Delete(c *gin.Context) {
id := c.Param("id")
var boardItem board
db.First(&boardItem, id)
db.Delete(&boardItem)
db.Unscoped().Delete(&boardItem) //db에서도 내용 영구적으로 삭제!
log.Println("DELETE")
c.Redirect(http.StatusSeeOther, "/api/v4")
}
3. form 안에 edit.html
{{ define "Edit" }}
<!DOCTYPE html>
<html>
<head>
<title>Edit Board Entry</title>
</head>
<body>
{{ template "Menu" . }}
<h2>Edit Board Entry</h2>
<form method="POST" action="/api/v4/update">
<input type="hidden" name="id" value="{{ .ID }}" />
<label for="title">Title</label>
<input type="text" id="title" name="title" value="{{ .Title }}" /><br />
<label for="content">Content</label>
<textarea id="content" name="content">{{ .Content }}</textarea><br />
<label for="writer">Writer</label>
<input type="text" id="writer" name="writer" value="{{ .Writer }}" /><br />
<input type="submit" value="Save Board" />
</form><br />
</body>
</html>
{{ end }}
4. form 안에 index.html
{{ define "Index" }}
{{ template "Menu" }}
<!DOCTYPE html>
<html>
<head>
<title>Board</title>
</head>
<body>
<h1>Board</h1>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Content</th>
<th>Writer</th>
<th>CreattedAt</th>
<th>View</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{{ range . }}
<tr>
<td>{{ .ID }}</td>
<td>{{ .Title }}</td>
<td>{{ .Content }}</td>
<td>{{ .Writer }}</td>
<td>{{ .CreatedAt }}</td>
<td><a href="/api/v4/show/id={{ .ID }}">View</a></td>
<td><a href="/api/v4/edit/id={{ .ID }}">Edit</a></td>
<td><a href="/api/v4/delete/id={{ .ID }}">Delete</a></td>
</tr>
{{ end }}
</tbody>
</table>
</body>
</html>
{{ end }}
5. form 안에 menu.html
{{ define "Menu" }}
<!DOCTYPE html>
<html>
<head>
<title>Menu</title>
</head>
<body>
<a href="/api/v4/">HOME</a> |
<a href="/api/v4/new">NEW</a>
</body>
</html>
{{ end }}
6. form 안에 new.html
{{ define "New" }}
{{ template "Menu" }}
<h2>Create New Board Entry</h2>
<form method="POST" action="/api/v4/insert">
<label> Title </label><input type="text" name="title" /><br />
<label> Content </label><textarea name="content"></textarea><br />
<label> Writer </label><input type="text" name="writer" /><br />
<input type="submit" value="Save Board" />
</form>
{{ end }}
7. form 안에 show.html
{{ define "Show" }}
<!DOCTYPE html>
<html>
<head>
<title>Board Entry #{{ .ID }}</title>
</head>
<body>
{{ template "Menu" }}
<h2>Board Entry #{{ .ID }}</h2>
<p>Title: {{ .Title }}</p>
<p>Content: {{ .Content }}</p>
<p>Writer: {{ .Writer }}</p>
<br /><a href="/api/v4/edit/{{ .ID }}">Edit</a>
</body>
</html>
{{ end }}
** url 창에 localhost:3000/api/v4/ 를 치면 기본 board 화면이 나온다.
** 상세조회
** 수정
'Language > Go' 카테고리의 다른 글
gorilla/mux - swagger 적용 (0) | 2023.11.16 |
---|---|
GO - sqlboiler (0) | 2023.10.26 |
Go[sqlboiler] - 간단한 게시판 만들기(1.20.8-v) (0) | 2023.10.19 |
Go 게시판 정리- 2 (0) | 2023.10.12 |
Go 시작 (0) | 2023.09.17 |