Project: alvinjo15/api_Marketing Commit: fb7f830d8c461ca591687b0a0db5e2176562132c Message: Initial commit --- .gitignore --- @@ -0,0 +1,15 @@ +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +vendor/ --- LICENSE.md --- @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2019 Vilbert Gunawan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. --- README.md --- @@ -0,0 +1 @@ +go-skeleton --- cmd/http/main.go --- @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + + "go-skeleton/internal/boot" + + _ "github.com/go-sql-driver/mysql" +) + +func main() { + if err := boot.HTTP(); err != nil { + fmt.Println("[HTTP] failed to boot http server due to " + err.Error()) + } +} --- files/etc/skeleton/skeleton.development.yaml --- @@ -0,0 +1,6 @@ +server: + port: ":8888" +database: + master: "root:@tcp(localhost:3306)/test" +api: + \ No newline at end of file --- go.mod --- @@ -0,0 +1,13 @@ +module go-skeleton + +go 1.13 + +require ( + github.com/go-sql-driver/mysql v1.4.0 + github.com/gorilla/mux v1.7.4 + github.com/jmoiron/sqlx v1.2.0 + github.com/pkg/errors v0.9.1 + github.com/stretchr/testify v1.5.1 + google.golang.org/appengine v1.6.5 // indirect + gopkg.in/yaml.v2 v2.2.8 +) --- go.sum --- @@ -0,0 +1,33 @@ +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-sql-driver/mysql v1.4.0 h1:7LxgVwFb2hIQtMm87NdgAVfXjnt4OePseqT1tKx+opk= +github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/gorilla/mux v1.7.4 h1:VuZ8uybHlWmqV03+zRzdwKL4tUnIp1MAQtp1mIFE1bc= +github.com/gorilla/mux v1.7.4/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= +github.com/jmoiron/sqlx v1.2.0 h1:41Ip0zITnmWNR/vHV+S4m+VoUivnWY5E4OJfLZjCJMA= +github.com/jmoiron/sqlx v1.2.0/go.mod h1:1FEQNm3xlJgrMD+FBdI9+xvCksHtbpVBBw5dYhBSsks= +github.com/lib/pq v1.0.0 h1:X5PMW56eZitiTeO7tKzZxFCSpbFZJtkMMooicw2us9A= +github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-sqlite3 v1.9.0 h1:pDRiWfl+++eC2FEFRy6jXmQlvp4Yh3z1MJKg4UeYM/4= +github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +google.golang.org/appengine v1.6.5 h1:tycE03LOZYQNhDpS27tcQdAzLCVMaj7QT2SXxebnpCM= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= --- internal/boot/http.go --- @@ -0,0 +1,52 @@ +package boot + +import ( + "log" + "net/http" + + "go-skeleton/internal/config" + + "github.com/jmoiron/sqlx" + + skeletonData "go-skeleton/internal/data/skeleton" + skeletonServer "go-skeleton/internal/delivery/http" + skeletonHandler "go-skeleton/internal/delivery/http/skeleton" + skeletonService "go-skeleton/internal/service/skeleton" +) + +// HTTP will load configuration, do dependency injection and then start the HTTP server +func HTTP() error { + var ( + s skeletonServer.Server // HTTP Server Object + sd skeletonData.Data // Domain data layer + ss skeletonService.Service // Domain service layer + sh *skeletonHandler.Handler // Domain handler + cfg *config.Config // Configuration object + ) + + err := config.Init() + if err != nil { + log.Fatalf("[CONFIG] Failed to initialize config: %v", err) + } + cfg = config.Get() + // Open MySQL DB Connection + db, err := sqlx.Open("mysql", cfg.Database.Master) + if err != nil { + log.Fatalf("[DB] Failed to initialize database connection: %v", err) + } + + // Diganti dengan domain yang anda buat + sd = skeletonData.New(db) + ss = skeletonService.New(sd) + sh = skeletonHandler.New(ss) + + s = skeletonServer.Server{ + Skeleton: sh, + } + + if err := s.Serve(cfg.Server.Port); err != http.ErrServerClosed { + return err + } + + return nil +} --- internal/config/config.go --- @@ -0,0 +1,70 @@ +package config + +import ( + "io/ioutil" + "os" + "path/filepath" + + "gopkg.in/yaml.v2" +) + +var ( + config *Config +) + +const ( + envDevelopment = "development" + envStaging = "staging" + envProduction = "production" +) + +type option struct { + configFile string +} + +// Init ... +func Init(opts ...Option) error { + opt := &option{ + configFile: getDefaultConfigFile(), + } + for _, optFunc := range opts { + optFunc(opt) + } + + out, err := ioutil.ReadFile(opt.configFile) + if err != nil { + return err + } + + return yaml.Unmarshal(out, &config) +} + +// Option ... +type Option func(*option) + +// WithConfigFile ... +func WithConfigFile(file string) Option { + return func(opt *option) { + opt.configFile = file + } +} + +func getDefaultConfigFile() string { + var ( + repoPath = filepath.Join(os.Getenv("GOPATH"), "src/go-skeleton") + configPath = filepath.Join(repoPath, "files/etc/skeleton/skeleton.environment.yaml") + env = os.Getenv("ENV") + ) + + if env != "" { + if env == envStaging { + configPath = "./skeleton.staging.yaml" + } + } + return configPath +} + +// Get ... +func Get() *Config { + return config +} --- internal/config/config_key.go --- @@ -0,0 +1,24 @@ +package config + +type ( + // Config ... + Config struct { + Server ServerConfig `yaml:"server"` + Database DatabaseConfig `yaml:"database"` + API APIConfig `yaml:"api"` + } + + // ServerConfig ... + ServerConfig struct { + Port string `yaml:"port"` + } + + // DatabaseConfig ... + DatabaseConfig struct { + Master string `yaml:"master"` + } + + // APIConfig ... + APIConfig struct { + } +) --- internal/data/skeleton/skeleton.go --- @@ -0,0 +1,61 @@ +package skeleton + +import ( + "context" + "log" + + "github.com/jmoiron/sqlx" +) + +type ( + // Data ... + Data struct { + db *sqlx.DB + stmt map[string]*sqlx.Stmt + } + + // statement ... + statement struct { + key string + query string + } +) + +// Tambahkan query di dalam const +// getAllUser = "GetAllUser" +// qGetAllUser = "SELECT * FROM users" +const () + +// Tambahkan query ke dalam key value order agar menjadi prepared statements +// readStmt = []statement{ +// {getAllUser, qGetAllUser}, +// } +var ( + readStmt = []statement{} +) + +// New ... +func New(db *sqlx.DB) Data { + d := Data{ + db: db, + } + + d.initStmt() + return d +} + +func (d *Data) initStmt() { + var ( + err error + stmts = make(map[string]*sqlx.Stmt) + ) + + for _, v := range readStmt { + stmts[v.key], err = d.db.PreparexContext(context.Background(), v.query) + if err != nil { + log.Fatalf("[DB] Failed to initialize statement key %v, err : %v", v.key, err) + } + } + + d.stmt = stmts +} --- internal/delivery/http/handler.go --- @@ -0,0 +1,49 @@ +package http + +import ( + "errors" + "log" + "net/http" + + "go-skeleton/pkg/response" + + "github.com/gorilla/mux" +) + +// Handler will initialize mux router and register handler +func (s *Server) Handler() *mux.Router { + r := mux.NewRouter() + // Jika tidak ditemukan, jangan diubah. + r.NotFoundHandler = http.HandlerFunc(notFoundHandler) + // Tambahan Prefix di depan API endpoint + router := r.PathPrefix("").Subrouter() + router.HandleFunc("/skeleton", s.Skeleton.SkeletonHandler).Methods("GET") + + return r +} + +func notFoundHandler(w http.ResponseWriter, r *http.Request) { + var ( + resp *response.Response + err error + errRes response.Error + ) + resp = &response.Response{} + defer resp.RenderJSON(w, r) + + err = errors.New("404 Not Found") + + if err != nil { + // Error response handling + errRes = response.Error{ + Code: 404, + Msg: "404 Not Found", + Status: true, + } + + log.Printf("[ERROR] %s %s - %v\n", r.Method, r.URL, err) + resp.StatusCode = 404 + resp.Error = errRes + return + } +} --- internal/delivery/http/server.go --- @@ -0,0 +1,24 @@ +package http + +import ( + "net/http" + + "go-skeleton/pkg/grace" +) + +// SkeletonHandler ... +type SkeletonHandler interface { + // Masukkan fungsi handler di sini + SkeletonHandler(w http.ResponseWriter, r *http.Request) +} + +// Server ... +type Server struct { + server *http.Server + Skeleton SkeletonHandler +} + +// Serve is serving HTTP gracefully on port x ... +func (s *Server) Serve(port string) error { + return grace.Serve(port, s.Handler()) +} --- internal/delivery/http/skeleton/skeleton.go --- @@ -0,0 +1,86 @@ +package skeleton + +import ( + "errors" + "log" + "net/http" + "strings" + + "go-skeleton/pkg/response" +) + +// ISkeletonSvc is an interface to Skeleton Service +// Masukkan function dari service ke dalam interface ini +type ISkeletonSvc interface { +} + +type ( + // Handler ... + Handler struct { + skeletonSvc ISkeletonSvc + } +) + +// New for bridging product handler initialization +func New(is ISkeletonSvc) *Handler { + return &Handler{ + skeletonSvc: is, + } +} + +// SkeletonHandler will receive request and return response +func (h *Handler) SkeletonHandler(w http.ResponseWriter, r *http.Request) { + var ( + resp *response.Response + result interface{} + metadata interface{} + err error + errRes response.Error + ) + resp = &response.Response{} + defer resp.RenderJSON(w, r) + + switch r.Method { + // Check if request method is GET + case http.MethodGet: + + // Check if request method is POST + case http.MethodPost: + + // Check if request method is PUT + case http.MethodPut: + + // Check if request method is DELETE + case http.MethodDelete: + + default: + err = errors.New("404") + } + + // If anything from service or data return an error + if err != nil { + // Error response handling + errRes = response.Error{ + Code: 101, + Msg: "Data Not Found", + Status: true, + } + // If service returns an error + if strings.Contains(err.Error(), "service") { + // Replace error with server error + errRes = response.Error{ + Code: 201, + Msg: "Failed to process request due to server error", + Status: true, + } + } + + log.Printf("[ERROR] %s %s - %v\n", r.Method, r.URL, err) + resp.Error = errRes + return + } + + resp.Data = result + resp.Metadata = metadata + log.Printf("[INFO] %s %s\n", r.Method, r.URL) +} --- internal/entity/skeleton/skeleton.go --- @@ -0,0 +1,7 @@ +package skeleton + +// Skeleton model +type Skeleton struct { + SkeletonID int `db:"skeleton_id" json:"skeleton_id"` + SkeletonName int `db:"skeleton_name" json:"skeleton_name"` +} --- internal/service/skeleton/skeleton.go --- @@ -0,0 +1,21 @@ +package skeleton + +// Data ... +// Masukkan function dari package data ke dalam interface ini +type Data interface { +} + +// Service ... +// Tambahkan variable sesuai banyak data layer yang dibutuhkan +type Service struct { + data Data +} + +// New ... +// Tambahkan parameter sesuai banyak data layer yang dibutuhkan +func New(data Data) Service { + // Assign variable dari parameter ke object + return Service{ + data: data, + } +} --- pkg/errors/.gitignore --- @@ -0,0 +1,24 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof --- pkg/errors/.travis.yml --- @@ -0,0 +1,15 @@ +language: go +go_import_path: github.com/pkg/errors +go: + - 1.4.x + - 1.5.x + - 1.6.x + - 1.7.x + - 1.8.x + - 1.9.x + - 1.10.x + - 1.11.x + - tip + +script: + - go test -v ./... --- pkg/errors/LICENSE --- @@ -0,0 +1,23 @@ +Copyright (c) 2015, Dave Cheney +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --- pkg/errors/README.md --- @@ -0,0 +1,52 @@ +# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) [![Sourcegraph](https://sourcegraph.com/github.com/pkg/errors/-/badge.svg)](https://sourcegraph.com/github.com/pkg/errors?badge) + +Package errors provides simple error handling primitives. + +`go get github.com/pkg/errors` + +The traditional error handling idiom in Go is roughly akin to +```go +if err != nil { + return err +} +``` +which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. + +## Adding context to an error + +The errors.Wrap function returns a new error that adds context to the original error. For example +```go +_, err := ioutil.ReadAll(r) +if err != nil { + return errors.Wrap(err, "read failed") +} +``` +## Retrieving the cause of an error + +Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. +```go +type causer interface { + Cause() error +} +``` +`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: +```go +switch err := errors.Cause(err).(type) { +case *MyError: + // handle specifically +default: + // unknown error +} +``` + +[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). + +## Contributing + +We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high. + +Before proposing a change, please discuss your change by raising an issue. + +## License + +BSD-2-Clause