feat: Adding initial server and migration system.
This commit is contained in:
parent
d92b828c63
commit
7e9bdbb313
10
go.mod
Normal file
10
go.mod
Normal 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
9
main.go
Normal file
@ -0,0 +1,9 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"WWWShop/wwwshop"
|
||||
)
|
||||
|
||||
func main() {
|
||||
wwwshop.New().Init();
|
||||
}
|
1
migrations/0000001_create_users_table.down.sql
Normal file
1
migrations/0000001_create_users_table.down.sql
Normal file
@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS users;
|
5
migrations/0000001_create_users_table.up.sql
Normal file
5
migrations/0000001_create_users_table.up.sql
Normal file
@ -0,0 +1,5 @@
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id serial PRIMARY KEY,
|
||||
username text UNIQUE NOT NULL,
|
||||
password text NOT NULL
|
||||
);
|
35
wwwshop/dao/database/database.go
Normal file
35
wwwshop/dao/database/database.go
Normal 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
24
wwwshop/wwwshop.go
Normal 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)
|
||||
}
|
Loading…
Reference in New Issue
Block a user