Skip to content

Commit

Permalink
go-gin-example
Browse files Browse the repository at this point in the history
  • Loading branch information
eddycjy committed Feb 16, 2018
0 parents commit 565e1a9
Show file tree
Hide file tree
Showing 271 changed files with 105,405 additions and 0 deletions.
19 changes: 19 additions & 0 deletions conf/app.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#debug or release
RUN_MODE = debug

[app]
PAGE_SIZE = 10
JWT_SECRET = 233

[server]
HTTP_PORT = 8000
READ_TIMEOUT = 60
WRITE_TIMEOUT = 60

[database]
TYPE = mysql
USER = root
PASSWORD = rootroot
HOST = 127.0.0.1:3306
NAME = blog
TABLE_PREFIX = blog_
23 changes: 23 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package main

import (
"fmt"
"net/http"

"gin-blog/routers"
"gin-blog/pkg/setting"
)

func main() {
router := routers.InitRouter()

s := &http.Server{
Addr: fmt.Sprintf(":%d", setting.HTTPPort),
Handler: router,
ReadTimeout: setting.ReadTimeout,
WriteTimeout: setting.WriteTimeout,
MaxHeaderBytes: 1 << 20,
}

s.ListenAndServe()
}
44 changes: 44 additions & 0 deletions middleware/jwt/jwt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package jwt

import (
"time"
"net/http"

"github.com/gin-gonic/gin"

"gin-blog/pkg/util"
"gin-blog/pkg/e"
)

func JWT() gin.HandlerFunc {
return func(c *gin.Context) {
var code int
var data interface{}

code = e.SUCCESS
token := c.Query("token")
if token == "" {
code = e.INVALID_PARAMS
} else {
claims, err := util.ParseToken(token)
if err != nil {
code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
} else if time.Now().Unix() > claims.ExpiresAt {
code = e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT
}
}

if code != e.SUCCESS {
c.JSON(http.StatusUnauthorized, gin.H{
"code" : code,
"msg" : e.GetMsg(code),
"data" : data,
})

c.Abort()
return
}

c.Next()
}
}
89 changes: 89 additions & 0 deletions models/article.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package models

import (
"time"

"github.com/jinzhu/gorm"
)

type Article struct {
Model

TagID int `json:"tag_id" gorm:"index"`
Tag Tag `json:"tag"`

Title string `json:"title"`
Desc string `json:"title"`
Content string `json:"content"`
CreatedBy string `json:"created_by"`
ModifiedBy string `json:"modified_by"`
State int `json:"state"`
}


func ExistArticleByID(id int) bool {
var article Article
db.Select("id").Where("id = ?", id).First(&article)

if article.ID > 0 {
return true
}

return false
}

func GetArticleTotal(maps interface {}) (count int){
db.Model(&Article{}).Where(maps).Count(&count)

return
}

func GetArticles(pageNum int, pageSize int, maps interface {}) (articles []Article) {
db.Preload("Tag").Where(maps).Offset(pageNum).Limit(pageSize).Find(&articles)

return
}

func GetArticle(id int) (article Article) {
db.Where("id = ?", id).First(&article)
db.Model(&article).Related(&article.Tag)

return
}

func EditArticle(id int, data interface {}) bool {
db.Model(&Article{}).Where("id = ?", id).Updates(data)

return true
}

func AddArticle(data map[string]interface {}) bool {
db.Create(&Article {
TagID : data["tag_id"].(int),
Title : data["title"].(string),
Desc : data["desc"].(string),
Content : data["content"].(string),
CreatedBy : data["created_by"].(string),
State : data["state"].(int),
})

return true
}

func DeleteArticle(id int) bool {
db.Where("id = ?", id).Delete(Article{})

return true
}

func (article *Article) BeforeCreate(scope *gorm.Scope) error {
scope.SetColumn("CreatedOn", time.Now().Unix())

return nil
}

func (article *Article) BeforeUpdate(scope *gorm.Scope) error {
scope.SetColumn("ModifiedOn", time.Now().Unix())

return nil
}
17 changes: 17 additions & 0 deletions models/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package models

type Auth struct {
ID int `gorm:"primary_key" json:"id"`
Username string `json:"username"`
Password string `json:"password"`
}

func CheckAuth(username, password string) bool {
var auth Auth
db.Select("id").Where(Auth{Username : username, Password : password}).First(&auth)
if auth.ID > 0 {
return true
}

return false
}
60 changes: 60 additions & 0 deletions models/models.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package models

import (
"log"
"fmt"

"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"

"gin-blog/pkg/setting"
)

var db *gorm.DB

type Model struct {
ID int `gorm:"primary_key" json:"id"`
CreatedOn int `json:"created_on"`
ModifiedOn int `json:"modified_on"`
}

func init() {
var (
err error
dbType, dbName, user, password, host, tablePrefix string
)

sec, err := setting.Cfg.GetSection("database")
if err != nil {
log.Fatal(2, "Fail to get section 'database': %v", err)
}

dbType = sec.Key("TYPE").String()
dbName = sec.Key("NAME").String()
user = sec.Key("USER").String()
password = sec.Key("PASSWORD").String()
host = sec.Key("HOST").String()
tablePrefix = sec.Key("TABLE_PREFIX").String()

db, err = gorm.Open(dbType, fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
user,
password,
host,
dbName))

if err != nil {
log.Println(err)
}

gorm.DefaultTableNameHandler = func (db *gorm.DB, defaultTableName string) string {
return tablePrefix + defaultTableName;
}

db.SingularTable(true)
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
}

func CloseDB() {
defer db.Close()
}
82 changes: 82 additions & 0 deletions models/tag.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package models

import (
"time"

"github.com/jinzhu/gorm"
)

type Tag struct {
Model

Name string `json:"name"`
CreatedBy string `json:"created_by"`
ModifiedBy string `json:"modified_by"`
State int `json:"state"`
}

func ExistTagByName(name string) bool {
var tag Tag
db.Select("id").Where("name = ?", name).First(&tag)
if tag.ID > 0 {
return true
}

return false
}

func AddTag(name string, state int, createdBy string) bool{
db.Create(&Tag {
Name : name,
State : state,
CreatedBy : createdBy,
})

return true
}

func GetTags(pageNum int, pageSize int, maps interface {}) (tags []Tag) {
db.Where(maps).Offset(pageNum).Limit(pageSize).Find(&tags)

return
}

func GetTagTotal(maps interface {}) (count int){
db.Model(&Tag{}).Where(maps).Count(&count)

return
}

func ExistTagByID(id int) bool {
var tag Tag
db.Select("id").Where("id = ?", id).First(&tag)
if tag.ID > 0 {
return true
}

return false
}

func DeleteTag(id int) bool {
db.Where("id = ?", id).Delete(&Tag{})

return true
}

func EditTag(id int, data interface {}) bool {
db.Model(&Tag{}).Where("id = ?", id).Updates(data)

return true
}

func (tag *Tag) BeforeCreate(scope *gorm.Scope) error {
scope.SetColumn("CreatedOn", time.Now().Unix())

return nil
}

func (tag *Tag) BeforeUpdate(scope *gorm.Scope) error {
scope.SetColumn("ModifiedOn", time.Now().Unix())

return nil
}
16 changes: 16 additions & 0 deletions pkg/e/code.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package e

const (
SUCCESS = 200
ERROR = 500
INVALID_PARAMS = 400

ERROR_EXIST_TAG = 10001
ERROR_NOT_EXIST_TAG = 10002
ERROR_NOT_EXIST_ARTICLE = 10003

ERROR_AUTH_CHECK_TOKEN_FAIL = 20001
ERROR_AUTH_CHECK_TOKEN_TIMEOUT = 20002
ERROR_AUTH_TOKEN = 20003
ERROR_AUTH = 20004
)
23 changes: 23 additions & 0 deletions pkg/e/msg.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package e

var MsgFlags = map[int]string {
SUCCESS : "ok",
ERROR : "fail",
INVALID_PARAMS : "请求参数错误",
ERROR_EXIST_TAG : "已存在该标签名称",
ERROR_NOT_EXIST_TAG : "该标签不存在",
ERROR_NOT_EXIST_ARTICLE : "该文章不存在",
ERROR_AUTH_CHECK_TOKEN_FAIL : "Token鉴权失败",
ERROR_AUTH_CHECK_TOKEN_TIMEOUT : "Token已超时",
ERROR_AUTH_TOKEN : "Token生成失败",
ERROR_AUTH : "Token错误",
}

func GetMsg(code int) string {
msg, ok := MsgFlags[code]
if ok {
return msg
}

return MsgFlags[ERROR]
}
Loading

0 comments on commit 565e1a9

Please sign in to comment.