├── .gitignore ├── README.md ├── bootstrap └── bootstrap.go ├── config ├── config.go ├── dev.ini └── prod.ini ├── database └── mysql.go ├── go.mod ├── go.sum ├── handler ├── auth_handler.go └── base_handler.go ├── log └── .gitignore ├── middleware ├── logger.go └── openid.go ├── model ├── base_model.go └── user_model.go ├── repository └── user_repository.go ├── router └── router.go ├── server.go ├── service └── user_service.go └── utils ├── const.go ├── http.go ├── log └── log.go ├── utils.go └── validator.go /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .idea 3 | tmp 4 | *.exe 5 | *.test 6 | *.prof -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Golang Web工程结构(echo) 2 | 3 | ## 依赖 4 | * Golang 1.11+ 5 | * export GO111MODULE=on 6 | 7 | ## 开发运行 8 | 9 | * 安装依赖 `go mod tidy` 10 | * 配置 `config/dev.ini` 11 | * `fresh server.go --env dev` 12 | 13 | -------------------------------------------------------------------------------- /bootstrap/bootstrap.go: -------------------------------------------------------------------------------- 1 | package bootstrap 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "golang-echo-layout/config" 7 | "golang-echo-layout/database" 8 | "golang-echo-layout/router" 9 | "golang-echo-layout/utils/log" 10 | "os" 11 | "os/signal" 12 | "time" 13 | ) 14 | 15 | func StartServer(ctx context.Context) { 16 | fmt.Println(ctx.Value("env")) 17 | config.NewConfig(ctx.Value("env").(string)) 18 | 19 | //New mysql 20 | database.NewMysql() 21 | if ctx.Value("env").(string) != "prod" { 22 | database.Mysql.LogMode(true) 23 | } 24 | defer database.Mysql.Close() 25 | 26 | // Logger init 27 | log.InitLog(config.Conf.App.LogLevel) 28 | 29 | s := router.Routers() 30 | 31 | //data, err := json.MarshalIndent(s.Routes(), "", " ") 32 | //if err != nil { 33 | // log.Error(err) 34 | //} 35 | //_ = ioutil.WriteFile("routes.json", data, 0644) 36 | 37 | go func() { 38 | log.Info("Start server at ", config.Conf.App.Addr) 39 | if err := s.Start(config.Conf.App.Addr); err != nil { 40 | log.Error("Shut down the server with error ", err) 41 | } 42 | }() 43 | 44 | quite := make(chan os.Signal) 45 | signal.Notify(quite, os.Interrupt) 46 | <-quite 47 | 48 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) 49 | defer cancel() 50 | 51 | if err := s.Shutdown(ctx); err != nil { 52 | log.Fatal("Server shutdown:", err) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "fmt" 5 | "github.com/labstack/gommon/log" 6 | "gopkg.in/ini.v1" 7 | "sync" 8 | ) 9 | 10 | type Config struct { 11 | App 12 | Mysql 13 | Wx 14 | } 15 | 16 | type ( 17 | App struct { 18 | Addr string `ini:"addr"` 19 | LogLevel string `ini:"log_level"` 20 | PageSize int `ini:"page_size"` 21 | } 22 | 23 | Mysql struct { 24 | Connect string `ini:"connect"` 25 | MaxIdle int `ini:"max_idle"` 26 | MaxOpen int `ini:"max_open"` 27 | } 28 | 29 | Wx struct { 30 | AppId string `ini:"app_id"` 31 | AppSecret string `ini:"app_secret"` 32 | } 33 | ) 34 | 35 | var ( 36 | Conf *Config 37 | once sync.Once 38 | ) 39 | 40 | func NewConfig(env string) { 41 | once.Do(func() { 42 | cfg, err := ini.ShadowLoad(fmt.Sprintf("config/%s.ini", env)) 43 | if err != nil { 44 | log.Fatal(err) 45 | } 46 | 47 | c := new(Config) 48 | err = cfg.MapTo(c) 49 | Conf = c 50 | }) 51 | } 52 | -------------------------------------------------------------------------------- /config/dev.ini: -------------------------------------------------------------------------------- 1 | [App] 2 | addr = :1213 3 | log_level = "DEBUG" # PANIC FATAL DEBUG INFO WARN ERROR 4 | page_size = 10 5 | 6 | [Mysql] 7 | connect = "root:admin@tcp(127.0.0.1:3306)/english_homework?charset=utf8&parseTime=True&loc=Local" 8 | max_idle = 10 9 | max_open = 100 10 | 11 | [Wx] 12 | app_id = xxxxxx 13 | app_secret = xxxxxx 14 | -------------------------------------------------------------------------------- /config/prod.ini: -------------------------------------------------------------------------------- 1 | [App] 2 | addr = :1213 3 | log_level = "WARN" # PANIC FATAL DEBUG INFO WARN ERROR 4 | page_size = 10 5 | 6 | [Mysql] 7 | connect = "root:12345@tcp(127.0.0.1:3306)/english_homework?charset=utf8&parseTime=True&loc=Local" 8 | max_idle = 10 9 | max_open = 100 10 | 11 | [Wx] 12 | app_id = xxxxxx 13 | app_secret = xxxxxx -------------------------------------------------------------------------------- /database/mysql.go: -------------------------------------------------------------------------------- 1 | package database 2 | 3 | import ( 4 | _ "github.com/go-sql-driver/mysql" 5 | "github.com/jinzhu/gorm" 6 | _ "github.com/jinzhu/gorm/dialects/mysql" 7 | "golang-echo-layout/config" 8 | "sync" 9 | ) 10 | 11 | var ( 12 | // Mysql DB 13 | Mysql *gorm.DB 14 | once sync.Once 15 | ) 16 | 17 | // NewMysql new mysql connection 18 | func NewMysql() *gorm.DB { 19 | once.Do(func() { 20 | db, err := gorm.Open("mysql", config.Conf.Mysql.Connect) 21 | if err != nil { 22 | panic(err) 23 | } 24 | Mysql = db 25 | Mysql.DB().SetMaxIdleConns(config.Conf.Mysql.MaxIdle) 26 | Mysql.DB().SetMaxOpenConns(config.Conf.Mysql.MaxOpen) 27 | }) 28 | return Mysql 29 | } 30 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module golang-echo-layout 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a 7 | github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect 8 | github.com/go-sql-driver/mysql v1.4.1 9 | github.com/imroc/req v0.2.4 10 | github.com/jinzhu/gorm v1.9.10 11 | github.com/labstack/echo v3.3.10+incompatible 12 | github.com/labstack/gommon v0.2.9 13 | github.com/sirupsen/logrus v1.4.2 14 | github.com/smartystreets/goconvey v0.0.0-20190731233626-505e41936337 // indirect 15 | gopkg.in/ini.v1 v1.46.0 16 | ) 17 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= 2 | cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= 3 | cloud.google.com/go v0.37.4 h1:glPeL3BQJsbF6aIIYfZizMwc5LTYz250bDMjttbBGAU= 4 | cloud.google.com/go v0.37.4/go.mod h1:NHPJ89PdicEuT9hdPXMROBD91xc5uRDxsMtSB16k7hw= 5 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= 6 | github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= 7 | github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= 8 | github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= 9 | github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= 10 | github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= 11 | github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a h1:idn718Q4B6AGu/h5Sxe66HYVdqdGu2l9Iebqhi/AEoA= 12 | github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY= 13 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= 14 | github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= 15 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 16 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 17 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 18 | github.com/denisenkom/go-mssqldb v0.0.0-20190515213511-eb9f6a1743f3 h1:tkum0XDgfR0jcVVXuTsYv/erY2NnEDqwRojbxR1rBYA= 19 | github.com/denisenkom/go-mssqldb v0.0.0-20190515213511-eb9f6a1743f3/go.mod h1:zAg7JM8CkOJ43xKXIj7eRO9kmWm/TW578qo+oDO6tuM= 20 | github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= 21 | github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= 22 | github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= 23 | github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= 24 | github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= 25 | github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y= 26 | github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0= 27 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= 28 | github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= 29 | github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= 30 | github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA= 31 | github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= 32 | github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= 33 | github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= 34 | github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= 35 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= 36 | github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= 37 | github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= 38 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 39 | github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= 40 | github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= 41 | github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ= 42 | github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= 43 | github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= 44 | github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= 45 | github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= 46 | github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= 47 | github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= 48 | github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= 49 | github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= 50 | github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= 51 | github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= 52 | github.com/imroc/req v0.2.4 h1:8XbvaQpERLAJV6as/cB186DtH5f0m5zAOtHEaTQ4ac0= 53 | github.com/imroc/req v0.2.4/go.mod h1:J9FsaNHDTIVyW/b5r6/Df5qKEEEq2WzZKIgKSajd1AE= 54 | github.com/jinzhu/gorm v1.9.10 h1:HvrsqdhCW78xpJF67g1hMxS6eCToo9PZH4LDB8WKPac= 55 | github.com/jinzhu/gorm v1.9.10/go.mod h1:Kh6hTsSGffh4ui079FHrR5Gg+5D0hgihqDcsDN2BBJY= 56 | github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= 57 | github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= 58 | github.com/jinzhu/now v1.0.1 h1:HjfetcXq097iXP0uoPCdnM4Efp5/9MsM0/M+XOTeR3M= 59 | github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= 60 | github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= 61 | github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= 62 | github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= 63 | github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= 64 | github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= 65 | github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= 66 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= 67 | github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= 68 | github.com/labstack/echo v3.3.10+incompatible h1:pGRcYk231ExFAyoAjAfD85kQzRJCRI8bbnE7CX5OEgg= 69 | github.com/labstack/echo v3.3.10+incompatible/go.mod h1:0INS7j/VjnFxD4E2wkz67b8cVwCLbBmJyDaka6Cmk1s= 70 | github.com/labstack/gommon v0.2.9 h1:heVeuAYtevIQVYkGj6A41dtfT91LrvFG220lavpWhrU= 71 | github.com/labstack/gommon v0.2.9/go.mod h1:E8ZTmW9vw5az5/ZyHWCp0Lw4OH2ecsaBP1C/NKavGG4= 72 | github.com/lib/pq v1.1.1 h1:sJZmqHoEaY7f+NPP8pgLB/WxulyR3fewgCM2qaSlBb4= 73 | github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= 74 | github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU= 75 | github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= 76 | github.com/mattn/go-isatty v0.0.8 h1:HLtExJ+uU2HOZ+wI0Tt5DtUDrx8yhUqDcp7fYERX4CE= 77 | github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= 78 | github.com/mattn/go-sqlite3 v1.10.0 h1:jbhqpg7tQe4SupckyijYiy0mJJ/pRyHvXf7JdWK860o= 79 | github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= 80 | github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= 81 | github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= 82 | github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 83 | github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 84 | github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= 85 | github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw= 86 | github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= 87 | github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 88 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 89 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 90 | github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= 91 | github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= 92 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= 93 | github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= 94 | github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= 95 | github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= 96 | github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= 97 | github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= 98 | github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= 99 | github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= 100 | github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= 101 | github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= 102 | github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= 103 | github.com/smartystreets/goconvey v0.0.0-20190731233626-505e41936337 h1:WN9BUFbdyOsSH/XohnWpXOlq9NBD5sGAB2FciQMUEe8= 104 | github.com/smartystreets/goconvey v0.0.0-20190731233626-505e41936337/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= 105 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 106 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 107 | github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= 108 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 109 | github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= 110 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 111 | github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= 112 | github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= 113 | github.com/valyala/fasttemplate v1.0.1 h1:tY9CJiPnMXf1ERmG2EyK7gNUd+c6RKGD0IfU8WdUSz8= 114 | github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= 115 | go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= 116 | golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= 117 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 118 | golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c h1:Vj5n4GlwjmQteupaxJ9+0FNOmBrHfq7vN4btdGoDZgI= 119 | golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 120 | golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= 121 | golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= 122 | golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= 123 | golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= 124 | golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 125 | golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 126 | golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 127 | golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 128 | golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 129 | golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 130 | golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 131 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 132 | golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= 133 | golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= 134 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 135 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 136 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 137 | golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 138 | golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 139 | golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 140 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 141 | golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 142 | golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 143 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 144 | golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 145 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 146 | golang.org/x/sys v0.0.0-20190602015325-4c4f7f33c9ed h1:uPxWBzB3+mlnjy9W58qY1j/cjyFjutgw/Vhan2zLy/A= 147 | golang.org/x/sys v0.0.0-20190602015325-4c4f7f33c9ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 148 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 149 | golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 150 | golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= 151 | golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 152 | golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 153 | golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= 154 | golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= 155 | golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= 156 | google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk= 157 | google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= 158 | google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508= 159 | google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= 160 | google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= 161 | google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= 162 | google.golang.org/genproto v0.0.0-20190404172233-64821d5d2107/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= 163 | google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= 164 | google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= 165 | gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= 166 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 167 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 168 | gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= 169 | gopkg.in/ini.v1 v1.46.0 h1:VeDZbLYGaupuvIrsYCEOe/L/2Pcs5n7hdO1ZTjporag= 170 | gopkg.in/ini.v1 v1.46.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= 171 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= 172 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 173 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 174 | honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= 175 | honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= 176 | honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= 177 | -------------------------------------------------------------------------------- /handler/auth_handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/imroc/req" 7 | "github.com/labstack/echo" 8 | "golang-echo-layout/config" 9 | "golang-echo-layout/repository" 10 | "golang-echo-layout/utils" 11 | "golang-echo-layout/utils/log" 12 | "net/http" 13 | ) 14 | 15 | type AuthHandler struct { 16 | } 17 | 18 | type Code2SessionResp struct { 19 | OpenId string `json:"openid"` 20 | SessionKey string `json:"session_key"` 21 | Unionid string `json:"unionid"` 22 | Errcode int `json:"errcode"` 23 | Errmsg string `json:"errmsg"` 24 | } 25 | 26 | func (a *AuthHandler) JSCode2Session(c echo.Context) error { 27 | r, err := req.Get(fmt.Sprintf("%s&appid=%s&secret=%s&js_code=%s", 28 | utils.Code2SessionUrl, 29 | config.Conf.Wx.AppId, 30 | config.Conf.Wx.AppSecret, 31 | c.QueryParam("code"), )) 32 | 33 | if err != nil { 34 | log.Error(err) 35 | return utils.NewHTTPError(http.StatusBadRequest, err.Error(), nil) 36 | } 37 | 38 | if r.Response().StatusCode != http.StatusOK { 39 | return utils.NewHTTPError(r.Response().StatusCode, "", nil) 40 | } 41 | 42 | var response Code2SessionResp 43 | respStr, _ := r.ToString() 44 | _ = json.Unmarshal([]byte(respStr), &response) 45 | if response.Errcode != 0 { 46 | return utils.NewHTTPError(http.StatusBadRequest, response.Errmsg, nil) 47 | } 48 | 49 | userRepo := repository.NewUserRepository() 50 | userRepo.FirstOrCreate(response.OpenId, response.Unionid, response.SessionKey) 51 | return utils.NewHTTPSuccess(c, "OK", map[string]interface{}{ 52 | "openid": response.OpenId, 53 | }) 54 | } 55 | -------------------------------------------------------------------------------- /handler/base_handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "github.com/labstack/echo" 5 | ) 6 | 7 | type BaseHandler struct { 8 | } 9 | 10 | func (b *BaseHandler) GetUserId(c echo.Context) uint { 11 | return c.Get("user_id").(uint) 12 | } 13 | -------------------------------------------------------------------------------- /log/.gitignore: -------------------------------------------------------------------------------- 1 | *.log -------------------------------------------------------------------------------- /middleware/logger.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "github.com/labstack/echo" 5 | "github.com/labstack/echo/middleware" 6 | log "github.com/sirupsen/logrus" 7 | "io" 8 | "os" 9 | "strconv" 10 | "time" 11 | ) 12 | 13 | type ( 14 | // LoggerConfig Logger configs 15 | LoggerConfig struct { 16 | Skipper middleware.Skipper 17 | Formatter log.Formatter 18 | Output io.Writer 19 | } 20 | ) 21 | 22 | var ( 23 | // DefaultLoggerConfig is the default Logger middleware config. 24 | DefaultLoggerConfig = LoggerConfig{ 25 | Skipper: middleware.DefaultSkipper, 26 | Formatter: &log.JSONFormatter{}, 27 | Output: os.Stdout, 28 | } 29 | ) 30 | 31 | // LoggerWithConfig Logger with config 32 | func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc { 33 | // Defaults 34 | if config.Skipper == nil { 35 | config.Skipper = DefaultLoggerConfig.Skipper 36 | } 37 | if config.Formatter == nil { 38 | config.Formatter = DefaultLoggerConfig.Formatter 39 | } 40 | if config.Output == nil { 41 | config.Output = DefaultLoggerConfig.Output 42 | } 43 | 44 | return func(next echo.HandlerFunc) echo.HandlerFunc { 45 | return func(c echo.Context) (err error) { 46 | if config.Skipper(c) { 47 | return next(c) 48 | } 49 | 50 | req := c.Request() 51 | res := c.Response() 52 | start := time.Now() 53 | if err = next(c); err != nil { 54 | c.Error(err) 55 | } 56 | 57 | stop := time.Now() 58 | id := req.Header.Get(echo.HeaderXRequestID) 59 | if id == "" { 60 | id = res.Header().Get(echo.HeaderXRequestID) 61 | } 62 | 63 | path := req.URL.Path 64 | if path == "" { 65 | path = "/" 66 | } 67 | status := res.Status 68 | latency := stop.Sub(start).String() 69 | 70 | log.WithFields(log.Fields{ 71 | "at": strconv.FormatInt(time.Now().UnixNano(), 10), 72 | "status": status, 73 | "ip": c.RealIP(), 74 | "id": id, 75 | "host": req.Host, 76 | "uri": req.RequestURI, 77 | "method": req.Method, 78 | "path": path, 79 | "proto": req.Proto, 80 | "refer": req.Referer(), 81 | "userAgent": req.UserAgent(), 82 | "size": strconv.FormatInt(res.Size, 10), 83 | "latency": latency, 84 | "header": req.Header, 85 | }).Info("Http request info") 86 | return nil 87 | } 88 | } 89 | } 90 | 91 | // Logger middleware logs request 92 | func Logger() echo.MiddlewareFunc { 93 | return LoggerWithConfig(DefaultLoggerConfig) 94 | } 95 | -------------------------------------------------------------------------------- /middleware/openid.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "errors" 5 | "github.com/labstack/echo" 6 | "golang-echo-layout/model" 7 | "golang-echo-layout/service" 8 | "golang-echo-layout/utils" 9 | "net/http" 10 | ) 11 | 12 | type UserContext struct { 13 | echo.Context 14 | } 15 | 16 | func (u *UserContext) UserInfo() (*model.User, error) { 17 | userService := service.NewUserService() 18 | user := userService.GetUserByOpenId(u.Request().Header.Get("open-id")) 19 | if user.ID == 0 { 20 | return nil, errors.New("Unauthorized") 21 | } 22 | 23 | return user, nil 24 | } 25 | 26 | func ValidateOpenId() echo.MiddlewareFunc { 27 | return func(next echo.HandlerFunc) echo.HandlerFunc { 28 | return func(c echo.Context) error { 29 | if len(c.Request().Header.Get("open-id")) == 0 { 30 | return utils.NewHTTPError(http.StatusUnauthorized, "账号验证不通过,请重新允许小程序授权", nil) 31 | } 32 | cc := &UserContext{c} 33 | user, err := cc.UserInfo() 34 | if err != nil { 35 | return utils.NewHTTPError(http.StatusUnauthorized, "账号验证不通过,请重新允许小程序授权!", nil) 36 | } 37 | 38 | cc.Context.Set("user_id", user.ID) 39 | return next(cc) 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /model/base_model.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import "time" 4 | 5 | type BaseModel struct { 6 | ID uint `json:"id" gorm:"primary_key;not null"` 7 | CreatedAt time.Time `json:"created_at"` 8 | UpdatedAt time.Time `json:"updated_at"` 9 | DeletedAt *time.Time `json:"-" sql:"index"` 10 | } 11 | -------------------------------------------------------------------------------- /model/user_model.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | type User struct { 4 | BaseModel 5 | OpenId string `json:"open_id"` 6 | NickName string `json:"nick_name"` 7 | SessionKey string `json:"session_key"` 8 | UnionId string `json:"union_id"` 9 | } 10 | -------------------------------------------------------------------------------- /repository/user_repository.go: -------------------------------------------------------------------------------- 1 | package repository 2 | 3 | import ( 4 | "golang-echo-layout/database" 5 | "golang-echo-layout/model" 6 | ) 7 | 8 | type UserRepository interface { 9 | FirstOrCreate(openId string, unionId string, sessionKey string) *model.User 10 | GetUserByOpenId(openId string) *model.User 11 | } 12 | 13 | func NewUserRepository() UserRepository { 14 | return &userDBRepository{} 15 | } 16 | 17 | type userDBRepository struct { 18 | } 19 | 20 | func (u *userDBRepository) FirstOrCreate(openId string, unionId string, sessionKey string) *model.User { 21 | user := new(model.User) 22 | database.Mysql.Where(model.User{OpenId: openId}).Attrs(model.User{UnionId: unionId, SessionKey: sessionKey}).FirstOrCreate(&user) 23 | return user 24 | } 25 | 26 | func (u *userDBRepository) GetUserByOpenId(openId string) *model.User { 27 | user := new(model.User) 28 | database.Mysql.Where("open_id = ?", openId).First(&user) 29 | return user 30 | } 31 | -------------------------------------------------------------------------------- /router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "github.com/labstack/echo" 5 | "github.com/labstack/echo/middleware" 6 | "golang-echo-layout/handler" 7 | myMiddleware "golang-echo-layout/middleware" 8 | "golang-echo-layout/service" 9 | "golang-echo-layout/utils" 10 | ) 11 | 12 | func Routers() *echo.Echo { 13 | e := echo.New() 14 | e.Use(middleware.StaticWithConfig(middleware.StaticConfig{ 15 | Root: "static", 16 | Browse: true, 17 | })) 18 | 19 | e.HTTPErrorHandler = utils.CustomHTTPErrorHandler 20 | e.Use(myMiddleware.Logger()) 21 | e.Use(middleware.Recover()) 22 | api := e.Group("/api") 23 | 24 | authHandler := handler.AuthHandler{} 25 | api.GET("/code2session", authHandler.JSCode2Session) 26 | 27 | return e 28 | } -------------------------------------------------------------------------------- /server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "flag" 6 | "golang-echo-layout/bootstrap" 7 | ) 8 | 9 | var ( 10 | env string 11 | showHelp bool 12 | ) 13 | 14 | func init() { 15 | flag.StringVar(&env, "env", "dev", "environment for server:[dev|prod]") 16 | flag.BoolVar(&showHelp, "h", false, "show help") 17 | flag.Parse() 18 | } 19 | 20 | func main() { 21 | if showHelp { 22 | flag.PrintDefaults() 23 | return 24 | } 25 | 26 | ctx := context.WithValue(context.Background(), "env", env) 27 | bootstrap.StartServer(ctx) 28 | 29 | } 30 | -------------------------------------------------------------------------------- /service/user_service.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "golang-echo-layout/model" 5 | "golang-echo-layout/repository" 6 | ) 7 | 8 | type UserService interface { 9 | GetUserByOpenId(openId string) *model.User 10 | } 11 | 12 | func NewUserService() UserService { 13 | return &userService{ 14 | userRepo: repository.NewUserRepository(), 15 | } 16 | } 17 | 18 | type userService struct { 19 | userRepo repository.UserRepository 20 | } 21 | 22 | func (u *userService) GetUserByOpenId(openId string) *model.User { 23 | return u.userRepo.GetUserByOpenId(openId) 24 | } 25 | -------------------------------------------------------------------------------- /utils/const.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | const Code2SessionUrl = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code" 4 | 5 | -------------------------------------------------------------------------------- /utils/http.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "github.com/labstack/echo" 5 | "golang-echo-layout/utils/log" 6 | "net/http" 7 | ) 8 | 9 | type ( 10 | HTTPError struct { 11 | Code int `json:"code"` 12 | Message string `json:"message"` 13 | Errors []string `json:"errors"` 14 | } 15 | HTTPSuccess struct { 16 | Code int `json:"code"` 17 | Message string `json:"message"` 18 | Data map[string]interface{} `json:"data"` 19 | } 20 | ) 21 | 22 | func (e *HTTPError) Error() string { 23 | return e.Message 24 | } 25 | 26 | func NewHTTPError(code int, message string, errors []string) *HTTPError { 27 | return &HTTPError{Code: code, Message: message, Errors: errors} 28 | } 29 | 30 | func NewHTTPSuccess(c echo.Context, message string, data map[string]interface{}) error { 31 | return c.JSON(http.StatusOK, map[string]interface{}{ 32 | "code": http.StatusOK, 33 | "message": message, 34 | "data": data, 35 | }) 36 | } 37 | 38 | func CustomHTTPErrorHandler(err error, c echo.Context) { 39 | var ( 40 | code = http.StatusInternalServerError 41 | msg string 42 | errs []string 43 | ) 44 | 45 | if he, ok := err.(*HTTPError); ok { 46 | code = he.Code 47 | msg = he.Message 48 | errs = he.Errors 49 | } else if ee, ok := err.(*echo.HTTPError); ok { 50 | code = ee.Code 51 | msg = ee.Message.(string) 52 | errs = SplitErrors(err) 53 | } else { 54 | msg = err.Error() 55 | } 56 | 57 | if !c.Response().Committed { 58 | if c.Request().Method == echo.HEAD { 59 | err = c.NoContent(code) 60 | } else { 61 | err = c.JSON(code, map[string]interface{}{ 62 | "code": code, 63 | "message": msg, 64 | "errors": errs, 65 | }) 66 | } 67 | if err != nil { 68 | log.Error(err) 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /utils/log/log.go: -------------------------------------------------------------------------------- 1 | package log 2 | 3 | import ( 4 | "github.com/sirupsen/logrus" 5 | "os" 6 | "strings" 7 | "time" 8 | ) 9 | 10 | type ( 11 | // MyLogger struct 12 | MyLogger struct { 13 | *logrus.Logger 14 | } 15 | ) 16 | 17 | var logger *MyLogger 18 | 19 | func init() { 20 | logger = &MyLogger{ 21 | logrus.New(), 22 | } 23 | } 24 | 25 | // Logger return MyLogger instance 26 | func Logger() *MyLogger { 27 | return logger 28 | } 29 | 30 | // InitLog set logger 31 | func InitLog(level string) { 32 | logger.SetLevel(getLogLevel(level)) 33 | logger.Formatter = &logrus.JSONFormatter{} 34 | logger.SetOutput(newLogFile()) 35 | } 36 | 37 | func newLogFile() *os.File { 38 | filename := "log/" + time.Now().Format("2006-01-02") + ".log" 39 | f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) 40 | if err != nil { 41 | panic(err) 42 | } 43 | 44 | return f 45 | } 46 | 47 | func getLogLevel(level string) logrus.Level { 48 | lv := strings.ToUpper(level) 49 | switch lv { 50 | case "PANIC": 51 | return logrus.PanicLevel 52 | case "FATAL": 53 | return logrus.FatalLevel 54 | case "ERROR": 55 | return logrus.ErrorLevel 56 | case "WARN": 57 | return logrus.WarnLevel 58 | case "INFO": 59 | return logrus.InfoLevel 60 | case "DEBUG": 61 | return logrus.DebugLevel 62 | default: 63 | return logrus.DebugLevel 64 | } 65 | } 66 | 67 | // Print logger.Print 68 | func Print(i ...interface{}) { 69 | logger.Print(i...) 70 | } 71 | 72 | // Printf logger.Printf 73 | func Printf(format string, args ...interface{}) { 74 | logger.Printf(format, args...) 75 | } 76 | 77 | // Debug logger.Debug 78 | func Debug(i ...interface{}) { 79 | logger.Debug(i...) 80 | } 81 | 82 | // Debugf logger.Debugf 83 | func Debugf(format string, args ...interface{}) { 84 | logger.Debugf(format, args...) 85 | } 86 | 87 | // Info logger.Info 88 | func Info(i ...interface{}) { 89 | logger.Info(i...) 90 | } 91 | 92 | // Infof logger.Infof 93 | func Infof(format string, args ...interface{}) { 94 | logger.Infof(format, args...) 95 | } 96 | 97 | // Warn logger.Warn 98 | func Warn(i ...interface{}) { 99 | logger.Warn(i...) 100 | } 101 | 102 | // Warnf logger.Warnf 103 | func Warnf(format string, args ...interface{}) { 104 | logger.Warnf(format, args...) 105 | } 106 | 107 | // Error logger.Error 108 | func Error(i ...interface{}) { 109 | logger.Error(i...) 110 | } 111 | 112 | // Errorf logger.Errorf 113 | func Errorf(format string, args ...interface{}) { 114 | logger.Errorf(format, args...) 115 | } 116 | 117 | // Fatal logger.Fatal 118 | func Fatal(i ...interface{}) { 119 | logger.Fatal(i...) 120 | } 121 | 122 | // Fatalf logger.Fatalf 123 | func Fatalf(format string, args ...interface{}) { 124 | logger.Fatalf(format, args...) 125 | } 126 | 127 | // Panic logger.Panic 128 | func Panic(i ...interface{}) { 129 | logger.Panic(i...) 130 | } 131 | 132 | // Panicf logger.Panicf 133 | func Panicf(format string, args ...interface{}) { 134 | logger.Panicf(format, args...) 135 | } 136 | -------------------------------------------------------------------------------- /utils/utils.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "golang-echo-layout/config" 5 | "math" 6 | "reflect" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | // SplitErrors split err error to string slice 12 | func SplitErrors(err error) []string { 13 | return strings.Split(err.Error(), ";") 14 | } 15 | 16 | func InArray(needle interface{}, haystak interface{}) (exists bool, index int) { 17 | exists = false 18 | index = -1 19 | 20 | switch reflect.TypeOf(haystak).Kind() { 21 | case reflect.Slice: 22 | s := reflect.ValueOf(haystak) 23 | for i := 0; i < s.Len(); i++ { 24 | if reflect.DeepEqual(needle, s.Index(i).Interface()) { 25 | index = i 26 | exists = true 27 | return 28 | } 29 | } 30 | } 31 | 32 | return 33 | } 34 | 35 | func Pagination(payload map[string]interface{}, total int) (pagination map[string]interface{}) { 36 | pagination = map[string]interface{}{ 37 | "total": total, 38 | } 39 | if limit, ok := payload["per_page"]; ok { 40 | pagination["per_page"], _ = strconv.Atoi(limit.(string)) 41 | } else { 42 | pagination["per_page"] = config.Conf.App.PageSize 43 | } 44 | 45 | if page, ok := payload["page"]; ok { 46 | pagination["current_page"], _ = strconv.Atoi(page.(string)) 47 | } else { 48 | pagination["current_page"] = 1 49 | } 50 | 51 | pagination["total_pages"] = int(math.Ceil(float64(total) / float64(pagination["per_page"].(int)))) 52 | return 53 | } -------------------------------------------------------------------------------- /utils/validator.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "github.com/asaskevich/govalidator" 5 | "github.com/labstack/echo" 6 | "net/http" 7 | ) 8 | 9 | //func init() { 10 | // 11 | //} 12 | 13 | func ValidateRequestStrut(c echo.Context, data interface{}) *HTTPError { 14 | if err := c.Bind(data); err != nil { 15 | return NewHTTPError(http.StatusBadRequest, "参数验证失败", SplitErrors(err)) 16 | } 17 | 18 | if _, err := govalidator.ValidateStruct(data); err != nil { 19 | return NewHTTPError(http.StatusBadRequest, "参数验证失败", SplitErrors(err)) 20 | } 21 | 22 | return nil 23 | } 24 | --------------------------------------------------------------------------------