-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
16 changed files
with
1,019 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
package db | ||
|
||
import ( | ||
"database/sql/driver" | ||
"fmt" | ||
"log" | ||
"os" | ||
"reflect" | ||
"regexp" | ||
"strconv" | ||
"time" | ||
"unicode" | ||
) | ||
|
||
var ( | ||
DefaultGormLogger = GormLogger{log.New(os.Stdout, "[ORM] ", 0)} | ||
sqlRegexp = regexp.MustCompile(`\?`) | ||
numericPlaceHolderRegexp = regexp.MustCompile(`\$\d+`) | ||
) | ||
|
||
func isPrintable(s string) bool { | ||
for _, r := range s { | ||
if !unicode.IsPrint(r) { | ||
return false | ||
} | ||
} | ||
return true | ||
} | ||
|
||
var LogFormatter = func(values ...interface{}) (messages []interface{}) { | ||
if len(values) > 1 { | ||
var ( | ||
sql string | ||
formattedValues []string | ||
level = values[0] | ||
currentTime = time.Now().Format("2006/01/02 15:04:05") | ||
// source = fmt.Sprintf(" %v", values[1]) | ||
) | ||
|
||
messages = []interface{}{currentTime} | ||
|
||
if level == "sql" { | ||
// duration | ||
messages = append(messages, fmt.Sprintf("[%.2fms]", float64(values[2].(time.Duration).Nanoseconds()/1e4)/100.0)) | ||
// sql | ||
for _, value := range values[4].([]interface{}) { | ||
indirectValue := reflect.Indirect(reflect.ValueOf(value)) | ||
if indirectValue.IsValid() { | ||
value = indirectValue.Interface() | ||
if t, ok := value.(time.Time); ok { | ||
formattedValues = append(formattedValues, fmt.Sprintf("'%v'", t.Format("2006-01-02 15:04:05"))) | ||
} else if b, ok := value.([]byte); ok { | ||
if str := string(b); isPrintable(str) { | ||
formattedValues = append(formattedValues, fmt.Sprintf("'%v'", str)) | ||
} else { | ||
formattedValues = append(formattedValues, "'<binary>'") | ||
} | ||
} else if r, ok := value.(driver.Valuer); ok { | ||
if value, err := r.Value(); err == nil && value != nil { | ||
formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value)) | ||
} else { | ||
formattedValues = append(formattedValues, "NULL") | ||
} | ||
} else { | ||
formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value)) | ||
} | ||
} else { | ||
formattedValues = append(formattedValues, "NULL") | ||
} | ||
} | ||
|
||
// differentiate between $n placeholders or else treat like ? | ||
if numericPlaceHolderRegexp.MatchString(values[3].(string)) { | ||
sql = values[3].(string) | ||
for index, value := range formattedValues { | ||
placeholder := fmt.Sprintf(`\$%d([^\d]|$)`, index+1) | ||
sql = regexp.MustCompile(placeholder).ReplaceAllString(sql, value+"$1") | ||
} | ||
} else { | ||
formattedValuesLength := len(formattedValues) | ||
for index, value := range sqlRegexp.Split(values[3].(string), -1) { | ||
sql += value | ||
if index < formattedValuesLength { | ||
sql += formattedValues[index] | ||
} | ||
} | ||
} | ||
|
||
messages = append(messages, sql) | ||
messages = append(messages, fmt.Sprintf("\r\n%v", strconv.FormatInt(values[5].(int64), 10)+" rows affected or returned")) | ||
} else { | ||
messages = append(messages, values[2:]...) | ||
} | ||
} | ||
|
||
return | ||
} | ||
|
||
type logger interface { | ||
Print(v ...interface{}) | ||
} | ||
|
||
// Logger default logger | ||
type GormLogger struct { | ||
*log.Logger | ||
} | ||
|
||
// Print format & print log | ||
func (logger GormLogger) Print(values ...interface{}) { | ||
logger.Println(LogFormatter(values...)...) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
package db | ||
|
||
import ( | ||
"fmt" | ||
"log" | ||
|
||
"github.com/jinzhu/gorm" | ||
_ "github.com/jinzhu/gorm/dialects/sqlite" | ||
"github.com/penggy/EasyGoLib/utils" | ||
) | ||
|
||
type Model struct { | ||
ID string `structs:"id" gorm:"primary_key" form:"id" json:"id"` | ||
CreatedAt utils.DateTime `structs:"-" json:"createdAt" gorm:"type:datetime"` | ||
UpdatedAt utils.DateTime `structs:"-" json:"updatedAt" gorm:"type:datetime"` | ||
// DeletedAt *time.Time `sql:"index" structs:"-"` | ||
} | ||
|
||
var SQLite *gorm.DB | ||
|
||
func Init() (err error) { | ||
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTablename string) string { | ||
return "t_" + defaultTablename | ||
} | ||
dbFile := utils.DBFile() | ||
log.Println("db file -->", utils.DBFile()) | ||
SQLite, err = gorm.Open("sqlite3", fmt.Sprintf("%s?loc=Asia/Shanghai", dbFile)) | ||
if err != nil { | ||
return | ||
} | ||
// Sqlite cannot handle concurrent writes, so we limit sqlite to one connection. | ||
// see https://github.com/mattn/go-sqlite3/issues/274 | ||
SQLite.DB().SetMaxOpenConns(1) | ||
SQLite.SetLogger(DefaultGormLogger) | ||
SQLite.LogMode(false) | ||
return | ||
} | ||
|
||
func Close() { | ||
if SQLite != nil { | ||
SQLite.Close() | ||
SQLite = nil | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
package utils | ||
|
||
import ( | ||
"io" | ||
"io/ioutil" | ||
"os" | ||
"path/filepath" | ||
) | ||
|
||
// Copy copies src to dest, doesn't matter if src is a directory or a file | ||
func Copy(src, dest string) error { | ||
src = ExpandHomeDir(filepath.Clean(src)) | ||
dest = ExpandHomeDir(filepath.Clean(dest)) | ||
|
||
info, err := os.Stat(src) | ||
if err != nil { | ||
return err | ||
} | ||
return copy(src, dest, info) | ||
} | ||
|
||
// "info" must be given here, NOT nil. | ||
func copy(src, dest string, info os.FileInfo) error { | ||
if info.IsDir() { | ||
return dcopy(src, dest, info) | ||
} | ||
return fcopy(src, dest, info) | ||
} | ||
|
||
func fcopy(src, dest string, info os.FileInfo) error { | ||
f, err := os.Create(dest) | ||
if err != nil { | ||
return err | ||
} | ||
defer f.Close() | ||
|
||
if err = os.Chmod(f.Name(), info.Mode()); err != nil { | ||
return err | ||
} | ||
|
||
s, err := os.Open(src) | ||
if err != nil { | ||
return err | ||
} | ||
defer s.Close() | ||
|
||
_, err = io.Copy(f, s) | ||
return err | ||
} | ||
|
||
func dcopy(src, dest string, info os.FileInfo) error { | ||
if err := os.MkdirAll(dest, info.Mode()); err != nil { | ||
return err | ||
} | ||
|
||
infos, err := ioutil.ReadDir(src) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
for _, info := range infos { | ||
if err := copy( | ||
filepath.Join(src, info.Name()), | ||
filepath.Join(dest, info.Name()), | ||
info, | ||
); err != nil { | ||
return err | ||
} | ||
} | ||
|
||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
package utils | ||
|
||
import ( | ||
"database/sql/driver" | ||
"fmt" | ||
"log" | ||
"os" | ||
"reflect" | ||
"regexp" | ||
"strconv" | ||
"time" | ||
"unicode" | ||
) | ||
|
||
var ( | ||
DefaultGormLogger = GormLogger{log.New(os.Stdout, "[ORM] ", 0)} | ||
sqlRegexp = regexp.MustCompile(`\?`) | ||
numericPlaceHolderRegexp = regexp.MustCompile(`\$\d+`) | ||
) | ||
|
||
func isPrintable(s string) bool { | ||
for _, r := range s { | ||
if !unicode.IsPrint(r) { | ||
return false | ||
} | ||
} | ||
return true | ||
} | ||
|
||
var LogFormatter = func(values ...interface{}) (messages []interface{}) { | ||
if len(values) > 1 { | ||
var ( | ||
sql string | ||
formattedValues []string | ||
level = values[0] | ||
currentTime = time.Now().Format("2006/01/02 15:04:05") | ||
// source = fmt.Sprintf(" %v", values[1]) | ||
) | ||
|
||
messages = []interface{}{currentTime} | ||
|
||
if level == "sql" { | ||
// duration | ||
messages = append(messages, fmt.Sprintf("[%.2fms]", float64(values[2].(time.Duration).Nanoseconds()/1e4)/100.0)) | ||
// sql | ||
for _, value := range values[4].([]interface{}) { | ||
indirectValue := reflect.Indirect(reflect.ValueOf(value)) | ||
if indirectValue.IsValid() { | ||
value = indirectValue.Interface() | ||
if t, ok := value.(time.Time); ok { | ||
formattedValues = append(formattedValues, fmt.Sprintf("'%v'", t.Format("2006-01-02 15:04:05"))) | ||
} else if b, ok := value.([]byte); ok { | ||
if str := string(b); isPrintable(str) { | ||
formattedValues = append(formattedValues, fmt.Sprintf("'%v'", str)) | ||
} else { | ||
formattedValues = append(formattedValues, "'<binary>'") | ||
} | ||
} else if r, ok := value.(driver.Valuer); ok { | ||
if value, err := r.Value(); err == nil && value != nil { | ||
formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value)) | ||
} else { | ||
formattedValues = append(formattedValues, "NULL") | ||
} | ||
} else { | ||
formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value)) | ||
} | ||
} else { | ||
formattedValues = append(formattedValues, "NULL") | ||
} | ||
} | ||
|
||
// differentiate between $n placeholders or else treat like ? | ||
if numericPlaceHolderRegexp.MatchString(values[3].(string)) { | ||
sql = values[3].(string) | ||
for index, value := range formattedValues { | ||
placeholder := fmt.Sprintf(`\$%d([^\d]|$)`, index+1) | ||
sql = regexp.MustCompile(placeholder).ReplaceAllString(sql, value+"$1") | ||
} | ||
} else { | ||
formattedValuesLength := len(formattedValues) | ||
for index, value := range sqlRegexp.Split(values[3].(string), -1) { | ||
sql += value | ||
if index < formattedValuesLength { | ||
sql += formattedValues[index] | ||
} | ||
} | ||
} | ||
|
||
messages = append(messages, sql) | ||
messages = append(messages, fmt.Sprintf("\r\n%v", strconv.FormatInt(values[5].(int64), 10)+" rows affected or returned")) | ||
} else { | ||
messages = append(messages, values[2:]...) | ||
} | ||
} | ||
|
||
return | ||
} | ||
|
||
type logger interface { | ||
Print(v ...interface{}) | ||
} | ||
|
||
// Logger default logger | ||
type GormLogger struct { | ||
*log.Logger | ||
} | ||
|
||
// Print format & print log | ||
func (logger GormLogger) Print(values ...interface{}) { | ||
logger.Println(LogFormatter(values...)...) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
package utils | ||
|
||
import ( | ||
"net/http" | ||
"net/url" | ||
"strings" | ||
) | ||
|
||
func GetRequestHref(r *http.Request) string { | ||
scheme := "http://" | ||
if r.TLS != nil { | ||
scheme = "https://" | ||
} | ||
return strings.Join([]string{scheme, r.Host, r.RequestURI}, "") | ||
} | ||
|
||
func GetRequestHostname(r *http.Request) (hostname string) { | ||
if _url, err := url.Parse(GetRequestHref(r)); err == nil { | ||
hostname = _url.Hostname() | ||
} | ||
return | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
// +build !release | ||
|
||
package utils | ||
|
||
import ( | ||
"fmt" | ||
"io" | ||
"log" | ||
"os" | ||
) | ||
|
||
func Log(msg ...interface{}) { | ||
log.Output(2, fmt.Sprintln(msg...)) | ||
} | ||
|
||
func Logf(format string, msg ...interface{}) { | ||
log.Output(2, fmt.Sprintf(format, msg...)) | ||
} | ||
|
||
func GetLogWriter() io.Writer { | ||
return os.Stdout | ||
} | ||
|
||
func CloseLogWriter() { | ||
|
||
} |
Oops, something went wrong.