Add Models, Add Database

This commit is contained in:
hoernschen 2020-09-28 22:37:02 +02:00
parent 8f90344870
commit faee833481
21 changed files with 407 additions and 1 deletions

View file

@ -0,0 +1,20 @@
package utils
import (
"database/sql"
"log"
_ "github.com/mattn/go-sqlite3"
)
func InitDB(filepath string) *sql.DB {
log.Printf("Init DB")
db, err := sql.Open("sqlite3", filepath)
if err != nil {
panic(err)
}
if db == nil {
panic("db nil")
}
return db
}

23
utils/logger.go Normal file
View file

@ -0,0 +1,23 @@
package utils
import (
"log"
"net/http"
"time"
)
func APILogger(inner http.Handler, name string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner.ServeHTTP(w, r)
log.Printf(
"%s\t%s\t%s\t%s",
r.Method,
r.RequestURI,
name,
time.Since(start),
)
})
}

12
utils/router/route.go Normal file
View file

@ -0,0 +1,12 @@
package router
import "net/http"
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route

27
utils/router/router.go Normal file
View file

@ -0,0 +1,27 @@
package router
import (
"net/http"
"github.com/gorilla/mux"
"nutfactory.org/Matrix/utils"
)
func NewRouter(routes Routes) *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
var handler http.Handler
handler = route.HandlerFunc
handler = utils.APILogger(handler, route.Name)
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
}
return router
}