Compare commits
19 Commits
be2c3ae178
...
v1.4.0
Author | SHA1 | Date | |
---|---|---|---|
53a780343f | |||
8e4c5e3268 | |||
f18f512fea | |||
58328fe505 | |||
10e7830349 | |||
5f7e674d32 | |||
ec9c1a8fb5 | |||
242029f2e5 | |||
b1c65f2ab1 | |||
965139ea18 | |||
cf8aea5115 | |||
c510646c84 | |||
a4366c7395 | |||
073dfafb28 | |||
3fa5cf46d2 | |||
bd8b015f44 | |||
5a1cd77676 | |||
012906eee2 | |||
2a705483d9 |
22
.gitignore
vendored
22
.gitignore
vendored
@ -1,4 +1,26 @@
|
||||
# GoWeb specific
|
||||
env.json
|
||||
logs/
|
||||
*.log
|
||||
|
||||
# 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
|
||||
vendor/
|
||||
|
||||
# Go workspace file
|
||||
go.work
|
||||
|
||||
# IDE files
|
||||
/.idea
|
59
README.md
Normal file
59
README.md
Normal file
@ -0,0 +1,59 @@
|
||||
# GoWeb 🌐
|
||||
|
||||
GoWeb is a simple Go web framework that aims to only use the standard library. The overall file structure and
|
||||
development flow is inspired by larger frameworks like Laravel. It is partially ready for smaller projects if you are
|
||||
fine with getting your hands dirty, but I plan on having it ready to go for more serious projects when it hits version
|
||||
2.0.
|
||||
|
||||
<hr>
|
||||
|
||||
## Current features 🚀
|
||||
|
||||
- Routing/controllers
|
||||
- Templating
|
||||
- Simple database migration system
|
||||
- CSRF protection
|
||||
- Minimal user login/registration + sessions
|
||||
- Config file handling
|
||||
- Entire website compiles into a single binary (~10mb) (excluding env.json)
|
||||
- Minimal dependencies (just standard library, postgres driver, and experimental package for bcrypt)
|
||||
|
||||
<hr>
|
||||
|
||||
## When to use 🙂
|
||||
|
||||
- You need to build a dynamic web application with persistent data
|
||||
- You need to build a dynamic website using Go and need a good starting point
|
||||
- You need to build an API in Go and don't know where to start
|
||||
- Pretty much any use-case where you would use Laravel, Django, or Flask
|
||||
|
||||
## When not to use 🙃
|
||||
|
||||
- You need a static website (see [Hugo](https://gohugo.io/))
|
||||
- You need a simple blog (see [Hugo](https://gohugo.io/))
|
||||
- You need a simple site for your projects' documentation (see [Hugo](https://gohugo.io/))
|
||||
|
||||
## How to use 🤔
|
||||
|
||||
1. Clone
|
||||
2. Run `go get` to install dependencies
|
||||
3. Copy env_example.json to env.json and fill in the values
|
||||
4. Run `go run main.go` to start the server
|
||||
5. Start building your app!
|
||||
|
||||
## How to contribute 👨💻
|
||||
|
||||
- Open an issue on GitHub if you find a bug or have a feature request.
|
||||
- [Email](mailto:contact@mpatterson.xyz) me a patch if you want to contribute code.
|
||||
- Please include a good description of what the patch does and why it is needed, also include how you want to be
|
||||
credited in the commit message.
|
||||
|
||||
<hr>
|
||||
|
||||
### License and disclaimer 😤
|
||||
|
||||
- You are free to use this project under the terms of the MIT license. See LICENSE for more details.
|
||||
- You and you alone are responsible for the security and everything else regarding your application.
|
||||
- It is not required, but I ask that when you use this project you give me credit by linking to this repository.
|
||||
- I also ask that when releasing self-hosted or other end-user applications that you release it under
|
||||
the [GPLv3](https://www.gnu.org/licenses/gpl-3.0.html) license. This too is not required, but I would appreciate it.
|
@ -8,7 +8,8 @@ import (
|
||||
|
||||
// App contains and supplies available configurations and connections
|
||||
type App struct {
|
||||
Config config.Configuration // Configuration file
|
||||
Db *sql.DB // Database connection
|
||||
Res *embed.FS // Resources from the embedded filesystem
|
||||
Config config.Configuration // Configuration file
|
||||
Db *sql.DB // Database connection
|
||||
Res *embed.FS // Resources from the embedded filesystem
|
||||
ScheduledTasks Scheduled // Scheduled contains a struct of all scheduled functions
|
||||
}
|
||||
|
75
app/schedule.go
Normal file
75
app/schedule.go
Normal file
@ -0,0 +1,75 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Scheduled struct {
|
||||
EveryReboot []func(app *App)
|
||||
EverySecond []func(app *App)
|
||||
EveryMinute []func(app *App)
|
||||
EveryHour []func(app *App)
|
||||
EveryDay []func(app *App)
|
||||
EveryWeek []func(app *App)
|
||||
EveryMonth []func(app *App)
|
||||
EveryYear []func(app *App)
|
||||
}
|
||||
|
||||
type Task struct {
|
||||
Interval time.Duration
|
||||
Funcs []func(app *App)
|
||||
}
|
||||
|
||||
func RunScheduledTasks(app *App, poolSize int, stop <-chan struct{}) {
|
||||
// Run every time the server starts
|
||||
for _, f := range app.ScheduledTasks.EveryReboot {
|
||||
f(app)
|
||||
}
|
||||
|
||||
tasks := []Task{
|
||||
{Interval: time.Second, Funcs: app.ScheduledTasks.EverySecond},
|
||||
{Interval: time.Minute, Funcs: app.ScheduledTasks.EveryMinute},
|
||||
{Interval: time.Hour, Funcs: app.ScheduledTasks.EveryHour},
|
||||
{Interval: 24 * time.Hour, Funcs: app.ScheduledTasks.EveryDay},
|
||||
{Interval: 7 * 24 * time.Hour, Funcs: app.ScheduledTasks.EveryWeek},
|
||||
{Interval: 30 * 24 * time.Hour, Funcs: app.ScheduledTasks.EveryMonth},
|
||||
{Interval: 365 * 24 * time.Hour, Funcs: app.ScheduledTasks.EveryYear},
|
||||
}
|
||||
|
||||
// Set up task runners
|
||||
var wg sync.WaitGroup
|
||||
runners := make([]chan bool, len(tasks))
|
||||
for i, task := range tasks {
|
||||
runner := make(chan bool, poolSize)
|
||||
runners[i] = runner
|
||||
wg.Add(1)
|
||||
go func(task Task, runner chan bool) {
|
||||
defer wg.Done()
|
||||
ticker := time.NewTicker(task.Interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
for _, f := range task.Funcs {
|
||||
runner <- true
|
||||
go func(f func(app *App)) {
|
||||
defer func() { <-runner }()
|
||||
f(app)
|
||||
}(f)
|
||||
}
|
||||
case <-stop:
|
||||
return
|
||||
}
|
||||
}
|
||||
}(task, runner)
|
||||
}
|
||||
|
||||
// Wait for all goroutines to finish
|
||||
wg.Wait()
|
||||
|
||||
// Close channels
|
||||
for _, runner := range runners {
|
||||
close(runner)
|
||||
}
|
||||
}
|
@ -24,13 +24,14 @@ func (postController *PostController) Login(w http.ResponseWriter, r *http.Reque
|
||||
|
||||
username := r.FormValue("username")
|
||||
password := r.FormValue("password")
|
||||
remember := r.FormValue("remember") == "on"
|
||||
|
||||
if username == "" || password == "" {
|
||||
log.Println("Tried to login user with empty username or password")
|
||||
http.Redirect(w, r, "/login", http.StatusFound)
|
||||
}
|
||||
|
||||
_, err = models.AuthenticateUser(postController.App, w, username, password)
|
||||
_, err = models.AuthenticateUser(postController.App, w, username, password, remember)
|
||||
if err != nil {
|
||||
log.Println("Error authenticating user")
|
||||
log.Println(err)
|
||||
|
2
go.mod
2
go.mod
@ -4,5 +4,5 @@ go 1.20
|
||||
|
||||
require (
|
||||
github.com/lib/pq v1.10.7
|
||||
golang.org/x/crypto v0.6.0
|
||||
golang.org/x/crypto v0.7.0
|
||||
)
|
||||
|
4
go.sum
4
go.sum
@ -1,4 +1,4 @@
|
||||
github.com/lib/pq v1.10.7 h1:p7ZhMD+KsSRozJr34udlUrhboJwWAgCg34+/ZZNvZZw=
|
||||
github.com/lib/pq v1.10.7/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
golang.org/x/crypto v0.6.0 h1:qfktjS5LUO+fFKeJXZ+ikTRijMmljikvG68fpMMruSc=
|
||||
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=
|
||||
golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A=
|
||||
golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU=
|
||||
|
8
main.go
8
main.go
@ -53,6 +53,12 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
// Assign and run scheduled tasks
|
||||
appLoaded.ScheduledTasks = app.Scheduled{
|
||||
EveryReboot: []func(app *app.App){models.ScheduledSessionCleanup},
|
||||
EveryMinute: []func(app *app.App){models.ScheduledSessionCleanup},
|
||||
}
|
||||
|
||||
// Define Routes
|
||||
routes.GetRoutes(&appLoaded)
|
||||
routes.PostRoutes(&appLoaded)
|
||||
@ -70,6 +76,8 @@ func main() {
|
||||
// Wait for interrupt signal and shut down the server
|
||||
interrupt := make(chan os.Signal, 1)
|
||||
signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
|
||||
stop := make(chan struct{})
|
||||
go app.RunScheduledTasks(&appLoaded, 100, stop)
|
||||
<-interrupt
|
||||
log.Println("Interrupt signal received. Shutting down server...")
|
||||
|
||||
|
@ -22,10 +22,11 @@ func RunAllMigrations(app *app.App) error {
|
||||
}
|
||||
|
||||
session := Session{
|
||||
Id: 1,
|
||||
UserId: 1,
|
||||
AuthToken: "migrate",
|
||||
CreatedAt: time.Now(),
|
||||
Id: 1,
|
||||
UserId: 1,
|
||||
AuthToken: "migrate",
|
||||
RememberMe: false,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
err = database.Migrate(app, session)
|
||||
if err != nil {
|
||||
|
@ -10,28 +10,32 @@ import (
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
Id int64
|
||||
UserId int64
|
||||
AuthToken string
|
||||
CreatedAt time.Time
|
||||
Id int64
|
||||
UserId int64
|
||||
AuthToken string
|
||||
RememberMe bool
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
const sessionColumnsNoId = "\"UserId\", \"AuthToken\", \"CreatedAt\""
|
||||
const sessionColumnsNoId = "\"UserId\", \"AuthToken\",\"RememberMe\", \"CreatedAt\""
|
||||
const sessionColumns = "\"Id\", " + sessionColumnsNoId
|
||||
const sessionTable = "public.\"Session\""
|
||||
|
||||
const (
|
||||
selectSessionByAuthToken = "SELECT " + sessionColumns + " FROM " + sessionTable + " WHERE \"AuthToken\" = $1"
|
||||
selectAuthTokenIfExists = "SELECT EXISTS(SELECT 1 FROM " + sessionTable + " WHERE \"AuthToken\" = $1)"
|
||||
insertSession = "INSERT INTO " + sessionTable + " (" + sessionColumnsNoId + ") VALUES ($1, $2, $3) RETURNING \"Id\""
|
||||
deleteSessionByAuthToken = "DELETE FROM " + sessionTable + " WHERE \"AuthToken\" = $1"
|
||||
selectSessionByAuthToken = "SELECT " + sessionColumns + " FROM " + sessionTable + " WHERE \"AuthToken\" = $1"
|
||||
selectAuthTokenIfExists = "SELECT EXISTS(SELECT 1 FROM " + sessionTable + " WHERE \"AuthToken\" = $1)"
|
||||
insertSession = "INSERT INTO " + sessionTable + " (" + sessionColumnsNoId + ") VALUES ($1, $2, $3, $4) RETURNING \"Id\""
|
||||
deleteSessionByAuthToken = "DELETE FROM " + sessionTable + " WHERE \"AuthToken\" = $1"
|
||||
deleteSessionsOlderThan30Days = "DELETE FROM " + sessionTable + " WHERE \"CreatedAt\" < NOW() - INTERVAL '30 days'"
|
||||
deleteSessionsOlderThan6Hours = "DELETE FROM " + sessionTable + " WHERE \"CreatedAt\" < NOW() - INTERVAL '6 hours' AND \"RememberMe\" = false"
|
||||
)
|
||||
|
||||
// CreateSession creates a new session for a user
|
||||
func CreateSession(app *app.App, w http.ResponseWriter, userId int64) (Session, error) {
|
||||
func CreateSession(app *app.App, w http.ResponseWriter, userId int64, remember bool) (Session, error) {
|
||||
session := Session{}
|
||||
session.UserId = userId
|
||||
session.AuthToken = generateAuthToken(app)
|
||||
session.RememberMe = remember
|
||||
session.CreatedAt = time.Now()
|
||||
|
||||
// If the AuthToken column for any user matches the token, set existingAuthToken to true
|
||||
@ -46,11 +50,11 @@ func CreateSession(app *app.App, w http.ResponseWriter, userId int64) (Session,
|
||||
// If duplicate token found, recursively call function until unique token is generated
|
||||
if existingAuthToken == true {
|
||||
log.Println("Duplicate token found in sessions table, generating new token...")
|
||||
return CreateSession(app, w, userId)
|
||||
return CreateSession(app, w, userId, remember)
|
||||
}
|
||||
|
||||
// Insert session into database
|
||||
err = app.Db.QueryRow(insertSession, session.UserId, session.AuthToken, session.CreatedAt).Scan(&session.Id)
|
||||
err = app.Db.QueryRow(insertSession, session.UserId, session.AuthToken, session.RememberMe, session.CreatedAt).Scan(&session.Id)
|
||||
if err != nil {
|
||||
log.Println("Error inserting session into database")
|
||||
return Session{}, err
|
||||
@ -75,13 +79,25 @@ func generateAuthToken(app *app.App) string {
|
||||
|
||||
// createSessionCookie creates a new session cookie
|
||||
func createSessionCookie(app *app.App, w http.ResponseWriter, session Session) {
|
||||
cookie := &http.Cookie{
|
||||
Name: "session",
|
||||
Value: session.AuthToken,
|
||||
Path: "/",
|
||||
MaxAge: 86400,
|
||||
HttpOnly: true,
|
||||
Secure: true,
|
||||
cookie := &http.Cookie{}
|
||||
if session.RememberMe {
|
||||
cookie = &http.Cookie{
|
||||
Name: "session",
|
||||
Value: session.AuthToken,
|
||||
Path: "/",
|
||||
MaxAge: 2592000 * 1000, // 30 days in ms
|
||||
HttpOnly: true,
|
||||
Secure: true,
|
||||
}
|
||||
} else {
|
||||
cookie = &http.Cookie{
|
||||
Name: "session",
|
||||
Value: session.AuthToken,
|
||||
Path: "/",
|
||||
MaxAge: 21600 * 1000, // 6 hours in ms
|
||||
HttpOnly: true,
|
||||
Secure: true,
|
||||
}
|
||||
}
|
||||
|
||||
http.SetCookie(w, cookie)
|
||||
@ -112,3 +128,22 @@ func DeleteSessionByAuthToken(app *app.App, w http.ResponseWriter, authToken str
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ScheduledSessionCleanup deletes expired sessions from the database
|
||||
func ScheduledSessionCleanup(app *app.App) {
|
||||
// Delete sessions older than 30 days (remember me sessions)
|
||||
_, err := app.Db.Exec(deleteSessionsOlderThan30Days)
|
||||
if err != nil {
|
||||
log.Println("Error deleting 30 day expired sessions from database")
|
||||
log.Println(err)
|
||||
}
|
||||
|
||||
// Delete sessions older than 6 hours
|
||||
_, err = app.Db.Exec(deleteSessionsOlderThan6Hours)
|
||||
if err != nil {
|
||||
log.Println("Error deleting 6 hour expired sessions from database")
|
||||
log.Println(err)
|
||||
}
|
||||
|
||||
log.Println("Deleted expired sessions from database")
|
||||
}
|
||||
|
@ -98,7 +98,7 @@ func CreateUser(app *app.App, username string, password string, createdAt time.T
|
||||
}
|
||||
|
||||
// AuthenticateUser validates the password for the specified user
|
||||
func AuthenticateUser(app *app.App, w http.ResponseWriter, username string, password string) (Session, error) {
|
||||
func AuthenticateUser(app *app.App, w http.ResponseWriter, username string, password string, remember bool) (Session, error) {
|
||||
var user User
|
||||
|
||||
// Query row by username
|
||||
@ -114,7 +114,7 @@ func AuthenticateUser(app *app.App, w http.ResponseWriter, username string, pass
|
||||
log.Println("Authentication error (incorrect password) for user:" + username)
|
||||
return Session{}, err
|
||||
} else {
|
||||
return CreateSession(app, w, user.Id)
|
||||
return CreateSession(app, w, user.Id, remember)
|
||||
}
|
||||
}
|
||||
|
||||
@ -133,14 +133,4 @@ func LogoutUser(app *app.App, w http.ResponseWriter, r *http.Request) {
|
||||
log.Println("Error deleting session by AuthToken")
|
||||
return
|
||||
}
|
||||
|
||||
// Delete cookie
|
||||
cookie = &http.Cookie{
|
||||
Name: "session",
|
||||
Value: "",
|
||||
Path: "/",
|
||||
MaxAge: -1,
|
||||
}
|
||||
|
||||
http.SetCookie(w, cookie)
|
||||
}
|
||||
|
@ -23,7 +23,7 @@ func GetRoutes(app *app.App) {
|
||||
}
|
||||
staticHandler := http.FileServer(http.FS(staticFS))
|
||||
http.Handle("/static/", http.StripPrefix("/static/", staticHandler))
|
||||
log.Println("Serving static files from embedded FS")
|
||||
log.Println("Serving static files from embedded file system /static")
|
||||
|
||||
// Pages
|
||||
http.HandleFunc("/", getController.ShowHome)
|
||||
|
@ -7,9 +7,11 @@
|
||||
<input name="csrf_token" type="hidden" value="{{ .CsrfToken }}">
|
||||
|
||||
<label for="username">Username:</label><br>
|
||||
<input id="username" name="username" type="text" value="John"><br><br>
|
||||
<input id="username" name="username" type="text" placeholder="John"><br><br>
|
||||
<label for="password">Password:</label><br>
|
||||
<input id="password" name="password" type="password"><br><br>
|
||||
<label for="remember">Remember Me:</label>
|
||||
<input id="remember" type="checkbox" name="remember"><br><br>
|
||||
<input type="submit" value="Submit">
|
||||
</form>
|
||||
</div>
|
||||
|
@ -7,7 +7,7 @@
|
||||
<input name="csrf_token" type="hidden" value="{{ .CsrfToken }}">
|
||||
|
||||
<label for="username">Username:</label><br>
|
||||
<input id="username" name="username" type="text" value="John"><br><br>
|
||||
<input id="username" name="username" type="text" placeholder="John"><br><br>
|
||||
<label for="password">Password:</label><br>
|
||||
<input id="password" name="password" type="password"><br><br>
|
||||
<input type="submit" value="Submit">
|
||||
|
Reference in New Issue
Block a user