feat: Adding initial server and migration system.

This commit is contained in:
sergiotarxz 2021-01-30 03:11:55 +01:00
parent d92b828c63
commit 7e9bdbb313
Signed by: sergiotarxz
GPG Key ID: E5903508B6510AC2
6 changed files with 84 additions and 0 deletions

10
go.mod Normal file
View File

@ -0,0 +1,10 @@
module WWWShop
go 1.15
require (
github.com/go-pg/pg/v10 v10.7.4 // indirect
github.com/golang-migrate/migrate/v4 v4.14.1
github.com/howeyc/fsnotify v0.9.0 // indirect
github.com/lib/pq v1.8.0
)

9
main.go Normal file
View File

@ -0,0 +1,9 @@
package main
import (
"WWWShop/wwwshop"
)
func main() {
wwwshop.New().Init();
}

View File

@ -0,0 +1 @@
DROP TABLE IF EXISTS users;

View File

@ -0,0 +1,5 @@
CREATE TABLE IF NOT EXISTS users (
id serial PRIMARY KEY,
username text UNIQUE NOT NULL,
password text NOT NULL
);

View File

@ -0,0 +1,35 @@
package database
import (
"database/sql"
"fmt"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
_ "github.com/lib/pq"
"log"
"os"
)
func DB() *sql.DB {
db, err := sql.Open("postgres", os.Getenv("DATABASE_URL"))
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
os.Exit(1)
}
return db
}
func Migrate(db *sql.DB) {
driver, err := postgres.WithInstance(db, &postgres.Config{})
if err != nil {
log.Fatal(err)
}
m, err := migrate.NewWithDatabaseInstance("file://migrations", "postgres", driver)
if err != nil {
log.Fatal(err)
}
if err := m.Up(); err != nil {
log.Fatal(err)
}
}

24
wwwshop/wwwshop.go Normal file
View File

@ -0,0 +1,24 @@
package wwwshop
import (
"net/http"
"fmt"
d "WWWShop/wwwshop/dao/database"
)
type WWWShop struct {}
func New() WWWShop {
var self = WWWShop {};
return self;
}
func (self WWWShop) Init() {
var db = d.DB()
d.Migrate(db)
http.HandleFunc("/", func( w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello world")
})
http.ListenAndServe(":8080", nil)
}