使用環境
フレームワーク
・Gin(Webフレームワーク)
・Gorm(DB関連のフレームワーク)
DB
・Postgresql
テーブル定義
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
CREATE TABLE public.users ( id integer NOT NULL DEFAULT nextval('users_id_seq'::regclass), created_at timestamp with time zone, updated_at timestamp with time zone, deleted_at timestamp with time zone, user_id text NOT NULL, password text, regist_date text, last_login text, CONSTRAINT users_pkey PRIMARY KEY (id, user_id) ) WITH ( OIDS=FALSE ); ALTER TABLE public.users OWNER TO "USER"; CREATE INDEX idx_users_deleted_at ON public.users USING btree (deleted_at); |
画面関連の処理
・index.go
index.htmlのGet処理とログインボタン押下のPOST処理の実装を行います。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package web import ( "github.com/gin-gonic/gin" "net/http" "github/GoSumple/gin_sumple/go/db" ) func Index(ctx *gin.Context){ ctx.HTML(http.StatusOK, "index.html", gin.H{ "text": "hello", }) } func Login(ctx *gin.Context){ logintext:="" userid,_:=ctx.GetPostForm("userId") password, _:=ctx.GetPostForm("password") userinfo:=db.UserSelect(userid,password) if userinfo.UserId != "" { logintext="ok" }else{ logintext="false" } ctx.HTML(http.StatusOK, "index.html", gin.H{ "text": logintext, }) } |
・index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>Gin Application</title> </head> <body> <form method="post" action="/login"> <h1>Login</h1> <input type="text" name="userId"><br> <input type="password" name="password"> <input type="submit" value="ログイン"> {{.text}} </form> </body> </html> |
画面のPOST、GETを定義する
・router.go
1 2 3 4 5 6 7 8 9 10 11 12 |
package web import ( "github.com/gin-gonic/gin" ) func Router(){ r := gin.Default() r.LoadHTMLGlob("content/html/*") r.GET("/", Index) // ログイン画面(GET処理) r.POST("/login", Login) // ログイン画面(POST処理) r.Run(":8080") } |
データベース関連の処理
・dbConnect.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package db import ( "github.com/jinzhu/gorm" _ "github.com/lib/pq" ) func GormConnect() *gorm.DB { //接続するDBの情報を定義 DBMS := "postgres" USER := "USER" PASS := "password" PROTOCOL := "localhost:5432" DBNAME := "GODB" CONNECT := DBMS+"://"+USER+":"+PASS+"@"+PROTOCOL+"/"+DBNAME+"?sslmode=disable" db,err := gorm.Open(DBMS, CONNECT) if err != nil { panic(err.Error()) } return db } |
・User.go
1 2 3 4 5 6 7 8 9 10 |
package data import "github.com/jinzhu/gorm" type User struct { gorm.Model UserId string `gorm:"primary_key"` Password string RegistDate string LastLogin string } |
・UserDb.go
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package db import ( "github/GoSumple/gin_sumple/go/data" ) //ユーザIdとパスワードをもとにユーザの情報を取得する func UserSelect(userId string,password string) data.User{ d := GormConnect() selData := data.User{} d.First(&selData,"user_id=? and password = ?",userId,password) defer d.Close() return selData } |
実際の画面
localhost:8080にアクセスすると下記の画面が表示されます。
ログインに成功すると文字列「hello」の箇所が「ok」に切り替わります。
ログインに失敗すると「false」に切り替わります。