echo framework validator (Partial Source) > IT 기술백서

/app/controllers/validator.go

[code] 

package controllers

import (

  “github.com/dlclark/regexp2”

  “github.com/go-playground/validator”

)

type CustomValidator struct {

  validator *validator.Validate

}

// Validate

func (c *CustomValidator) Validate(i interface{}) error {

  return c.validator.Struct(i)

}

// Password Add Custom Rule

func (c *CustomValidator) Password(fl validator.FieldLevel) bool {

  pattern := regexp2.MustCompile(`^.*(?=^.{6,20}$)(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$%^&+=]).*$`, regexp2.RE2)

  r, _ := pattern.MatchString(fl.Field().String())

  return r

}

// CreateValidator Create Object

func CreateValidator() *CustomValidator {

  v := &CustomValidator{}

  v.validator = validator.New()

  v.validator.RegisterValidation(“password”, v.Password)

  return v

}

[/code]

 

/app/models/User.go

[code]

package models

import (

  “time”

  “github.com/jinzhu/gorm”

  “golang.org/x/crypto/bcrypt”

)

type User struct {

  ID        uint32    `gorm:”primary_key;auto_increment” json:”id”`

  Email     string    `gorm:”size:100;not null;unique” json:”email” validate:”required,email”`

  Password  string    `gorm:”size:255;not null;” json:”password” validate:”required,password”`

  Name      string    `gorm:”size:255;not null;” json:”name” validate:”required”`

  CreatedAt time.Time `gorm:”default:CURRENT_TIMESTAMP” json:”created_at”`

  UpdatedAt time.Time `gorm:”default:CURRENT_TIMESTAMP” json:”updated_at”`

}

func (u *User) Hash(password string) (string, error) {

  h, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)

  if err != nil {

    return “”, err

  }

  return string(h), nil

}

func (u *User) InsertUser(db *gorm.DB) (*User, error) {

  u.Password, _ = u.Hash(u.Password)

  u.CreatedAt = time.Now()

  u.UpdatedAt = time.Now()

  err := db.Debug().Create(u).Error

  if err != nil {

    return &User{}, err

  }

  return u, nil

}

[/code]

 

/app/controllers/base.go

[code]

package controllers

import (

  “fmt”

  “log”

  “github.com/jinzhu/gorm”

  “github.com/labstack/echo”

  “github.com/labstack/echo/middleware”

  “githumb.com/hyuk-june/echotest/app/models”

  _ “github.com/go-sql-driver/mysql”

)

type (

  Server struct {

  }

)

var e *echo.Echo

var db *gorm.DB

func (s *Server) Initialize(Dbdriver, DbUser, DbPassword, DbPort, DbHost, DbName string) {

  var err error

  // Open DB

  DBURL := fmt.Sprintf(“%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local”, DbUser, DbPassword, DbHost, DbPort, DbName)

  db, err = gorm.Open(Dbdriver, DBURL)

  if err != nil {

    fmt.Printf(“Cannot Connect to %s database”, Dbdriver)

    log.Fatal(“This is the error:”, err)

  } else {

    fmt.Printf(“We are connected to the %s database”, Dbdriver)

  }

  // db Migrate

  db.Debug().AutoMigrate(

    &models.User{},

  )

  e = echo.New()

  // Set validator

  e.Validator = CreateValidator()

  s.initRoutes() // 라우팅

}

func (s *Server) Run(addr string) {

  e.Logger.Fatal(e.Start(addr))

}

[/code]

 

/app/server.go

[code]

package app

import (

  “fmt”

  “log”

  “os”

  “github.com/joho/godotenv”

  “githumb.com/hyuk-june/echotest/app/controllers”

)

func Run() {

  err := godotenv.Load()

  if err != nil {

    log.Fatalf(“Error getting env, not comming through %v”, err)

  } else {

    fmt.Println(“We are getting the env values”)

  }

  server := controllers.Server{}

  server.Initialize(

    os.Getenv(“DB_DRIVER”),

    os.Getenv(“DB_USER”),

    os.Getenv(“DB_PASSWORD”),

    os.Getenv(“DB_PORT”),

    os.Getenv(“DB_HOST”),

    os.Getenv(“DB_NAME”),

  )

  server.Run(“:3000”)

}

[/code]

 

/main.go

[code]

package main

import (

  “githumb.com/hyuk-june/echotest/app”

)

func main() {

  app.Run()

}

[/code]

 

댓글 달기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

위로 스크롤