Skip to content

Instantly share code, notes, and snippets.

@locona
Created May 29, 2018 07:17
Show Gist options
  • Save locona/73b17099aadf824427ee860b385ed7cd to your computer and use it in GitHub Desktop.
Save locona/73b17099aadf824427ee860b385ed7cd to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"go/ast"
"reflect"
"regexp"
"strings"
"time"
"github.com/k0kubun/pp"
)
const (
tableName = "user_%s"
)
// Default user schema.
type User struct {
AppUserID string `json:"app_user_id"`
// Platform IDs
IosUUID string `json:"ios_uuid"`
AndroidUUID string `json:"android_uuid"`
// Social IDs
FacebookID string `json:"facebook_id"`
InstagramID string `json:"instagram_id"`
TwitterID string `json:"twitter_id"`
LinkedinID string `json:"linkedin_id"`
LineID string `json:"line_id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
Tel string `json:"tel"`
Address string `json:"address"`
City string `json:"city"`
State string `json:"state"`
Zip string `json:"zip"`
Age uint `json:"age"`
Gender string `json:"gender"`
AvatarUrl string `json:"avatar"`
Company string `json:"company"`
// CompanyRole like president, employee, manager.
CompanyRole string `json:"company_role"`
// OccupationType like lawyer, web engineer, doctor.
OccupationType string `json:"occupation_type"`
Cookie string `json:"cookie"`
BirthDay time.Time `json:"birthday"`
EntryDate time.Time `json:"entry_date"`
// AppID from reckoner table of mysql.
AppID string `json:"app_id" gorm:"-"`
}
// TableName is override gorm's function.
// ref: http://jinzhu.me/gorm/models.html#conventions
func (this User) TableName() string {
return fmt.Sprintf(tableName, this.AppID)
}
func (this User) HasColoumn(columns []string) bool {
reflectType := reflect.ValueOf(this).Type()
for i := 0; i < reflectType.NumField(); i++ {
if fieldStruct := reflectType.Field(i); ast.IsExported(fieldStruct.Name) {
pp.Println(convertCamelToSnake(fieldStruct.Name))
parseTagSetting(fieldStruct.Tag)
}
}
return true
}
func parseTagSetting(fieldTag reflect.StructTag) map[string]string {
setting := map[string]string{}
tags := strings.Split(fieldTag.Get("json"), ";")
for _, value := range tags {
v := strings.Split(value, ":")
k := strings.TrimSpace(strings.ToUpper(v[0]))
if len(v) >= 2 {
setting[k] = strings.Join(v[1:], ":")
} else {
setting[k] = k
}
}
return setting
}
func convertCamelToSnake(s string) string {
camel := regexp.MustCompile("(^[^A-Z]*|[A-Z]*)([A-Z][^A-Z]+|$)")
var a []string
for _, sub := range camel.FindAllStringSubmatch(s, -1) {
if sub[1] != "" {
a = append(a, sub[1])
}
if sub[2] != "" {
a = append(a, sub[2])
}
}
return strings.ToLower(strings.Join(a, "_"))
}
func main() {
var user User
s := []string{"1", "2"}
user.HasColoumn(s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment