Compare commits
19 Commits
v1.4.0
...
9670b7d717
Author | SHA1 | Date | |
---|---|---|---|
9670b7d717 | |||
a1438f4fe2 | |||
052fa689c7 | |||
f1fad7e4e3 | |||
b475da66da | |||
d0085ab2c3 | |||
58514f4c5f | |||
606f5df45a | |||
2a32a1b3ce | |||
eb36156c52 | |||
bada24884a | |||
05397c2b61 | |||
3d80b95f55 | |||
6da7d408f9 | |||
e993bcf317 | |||
9b231a73d6 | |||
34acd0fa8d | |||
71d3bd77d0 | |||
1451abcca4 |
1
.gitattributes
vendored
Normal file
1
.gitattributes
vendored
Normal file
@ -0,0 +1 @@
|
||||
* text=auto eol=lf
|
@ -12,9 +12,12 @@ fine with getting your hands dirty, but I plan on having it ready to go for more
|
||||
- Routing/controllers
|
||||
- Templating
|
||||
- Simple database migration system
|
||||
- Built in REST client
|
||||
- CSRF protection
|
||||
- Middleware
|
||||
- Minimal user login/registration + sessions
|
||||
- Config file handling
|
||||
- Scheduled tasks
|
||||
- Entire website compiles into a single binary (~10mb) (excluding env.json)
|
||||
- Minimal dependencies (just standard library, postgres driver, and experimental package for bcrypt)
|
||||
|
||||
|
@ -22,7 +22,6 @@ type Task struct {
|
||||
}
|
||||
|
||||
func RunScheduledTasks(app *App, poolSize int, stop <-chan struct{}) {
|
||||
// Run every time the server starts
|
||||
for _, f := range app.ScheduledTasks.EveryReboot {
|
||||
f(app)
|
||||
}
|
||||
@ -37,7 +36,6 @@ func RunScheduledTasks(app *App, poolSize int, stop <-chan struct{}) {
|
||||
{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 {
|
||||
@ -65,10 +63,8 @@ func RunScheduledTasks(app *App, poolSize int, stop <-chan struct{}) {
|
||||
}(task, runner)
|
||||
}
|
||||
|
||||
// Wait for all goroutines to finish
|
||||
wg.Wait()
|
||||
|
||||
// Close channels
|
||||
for _, runner := range runners {
|
||||
close(runner)
|
||||
}
|
||||
|
@ -43,7 +43,6 @@ func LoadConfig() Configuration {
|
||||
}
|
||||
}(file)
|
||||
|
||||
// Decode json config file to Configuration struct named config
|
||||
decoder := json.NewDecoder(file)
|
||||
Config := Configuration{}
|
||||
err = decoder.Decode(&Config)
|
||||
|
65
controllers/get.go
Normal file
65
controllers/get.go
Normal file
@ -0,0 +1,65 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"GoWeb/app"
|
||||
"GoWeb/models"
|
||||
"GoWeb/security"
|
||||
"GoWeb/templating"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Get is a wrapper struct for the App struct
|
||||
type Get struct {
|
||||
App *app.App
|
||||
}
|
||||
|
||||
func (g *Get) ShowHome(w http.ResponseWriter, _ *http.Request) {
|
||||
type dataStruct struct {
|
||||
Test string
|
||||
}
|
||||
|
||||
data := dataStruct{
|
||||
Test: "Hello World!",
|
||||
}
|
||||
|
||||
templating.RenderTemplate(g.App, w, "templates/pages/home.html", data)
|
||||
}
|
||||
|
||||
func (g *Get) ShowRegister(w http.ResponseWriter, r *http.Request) {
|
||||
type dataStruct struct {
|
||||
CsrfToken string
|
||||
}
|
||||
|
||||
CsrfToken, err := security.GenerateCsrfToken(w, r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
data := dataStruct{
|
||||
CsrfToken: CsrfToken,
|
||||
}
|
||||
|
||||
templating.RenderTemplate(g.App, w, "templates/pages/register.html", data)
|
||||
}
|
||||
|
||||
func (g *Get) ShowLogin(w http.ResponseWriter, r *http.Request) {
|
||||
type dataStruct struct {
|
||||
CsrfToken string
|
||||
}
|
||||
|
||||
CsrfToken, err := security.GenerateCsrfToken(w, r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
data := dataStruct{
|
||||
CsrfToken: CsrfToken,
|
||||
}
|
||||
|
||||
templating.RenderTemplate(g.App, w, "templates/pages/login.html", data)
|
||||
}
|
||||
|
||||
func (g *Get) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
models.LogoutUser(g.App, w, r)
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
}
|
@ -1,67 +0,0 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"GoWeb/app"
|
||||
"GoWeb/models"
|
||||
"GoWeb/security"
|
||||
"GoWeb/templating"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// GetController is a wrapper struct for the App struct
|
||||
type GetController struct {
|
||||
App *app.App
|
||||
}
|
||||
|
||||
func (getController *GetController) ShowHome(w http.ResponseWriter, _ *http.Request) {
|
||||
type dataStruct struct {
|
||||
Test string
|
||||
}
|
||||
|
||||
data := dataStruct{
|
||||
Test: "Hello World!",
|
||||
}
|
||||
|
||||
templating.RenderTemplate(getController.App, w, "templates/pages/home.html", data)
|
||||
}
|
||||
|
||||
func (getController *GetController) ShowRegister(w http.ResponseWriter, r *http.Request) {
|
||||
type dataStruct struct {
|
||||
CsrfToken string
|
||||
}
|
||||
|
||||
// Create csrf token
|
||||
CsrfToken, err := security.GenerateCsrfToken(w, r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
data := dataStruct{
|
||||
CsrfToken: CsrfToken,
|
||||
}
|
||||
|
||||
templating.RenderTemplate(getController.App, w, "templates/pages/register.html", data)
|
||||
}
|
||||
|
||||
func (getController *GetController) ShowLogin(w http.ResponseWriter, r *http.Request) {
|
||||
type dataStruct struct {
|
||||
CsrfToken string
|
||||
}
|
||||
|
||||
// Create csrf token
|
||||
CsrfToken, err := security.GenerateCsrfToken(w, r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
data := dataStruct{
|
||||
CsrfToken: CsrfToken,
|
||||
}
|
||||
|
||||
templating.RenderTemplate(getController.App, w, "templates/pages/login.html", data)
|
||||
}
|
||||
|
||||
func (getController *GetController) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
models.LogoutUser(getController.App, w, r)
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
}
|
@ -3,25 +3,17 @@ package controllers
|
||||
import (
|
||||
"GoWeb/app"
|
||||
"GoWeb/models"
|
||||
"GoWeb/security"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PostController is a wrapper struct for the App struct
|
||||
type PostController struct {
|
||||
// Post is a wrapper struct for the App struct
|
||||
type Post struct {
|
||||
App *app.App
|
||||
}
|
||||
|
||||
func (postController *PostController) Login(w http.ResponseWriter, r *http.Request) {
|
||||
// Validate csrf token
|
||||
_, err := security.VerifyCsrfToken(r)
|
||||
if err != nil {
|
||||
log.Println("Error verifying csrf token")
|
||||
return
|
||||
}
|
||||
|
||||
func (p *Post) Login(w http.ResponseWriter, r *http.Request) {
|
||||
username := r.FormValue("username")
|
||||
password := r.FormValue("password")
|
||||
remember := r.FormValue("remember") == "on"
|
||||
@ -31,7 +23,7 @@ func (postController *PostController) Login(w http.ResponseWriter, r *http.Reque
|
||||
http.Redirect(w, r, "/login", http.StatusFound)
|
||||
}
|
||||
|
||||
_, err = models.AuthenticateUser(postController.App, w, username, password, remember)
|
||||
_, err := models.AuthenticateUser(p.App, w, username, password, remember)
|
||||
if err != nil {
|
||||
log.Println("Error authenticating user")
|
||||
log.Println(err)
|
||||
@ -42,14 +34,7 @@ func (postController *PostController) Login(w http.ResponseWriter, r *http.Reque
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
}
|
||||
|
||||
func (postController *PostController) Register(w http.ResponseWriter, r *http.Request) {
|
||||
// Validate csrf token
|
||||
_, err := security.VerifyCsrfToken(r)
|
||||
if err != nil {
|
||||
log.Println("Error verifying csrf token")
|
||||
return
|
||||
}
|
||||
|
||||
func (p *Post) Register(w http.ResponseWriter, r *http.Request) {
|
||||
username := r.FormValue("username")
|
||||
password := r.FormValue("password")
|
||||
createdAt := time.Now()
|
||||
@ -60,7 +45,7 @@ func (postController *PostController) Register(w http.ResponseWriter, r *http.Re
|
||||
http.Redirect(w, r, "/register", http.StatusFound)
|
||||
}
|
||||
|
||||
_, err = models.CreateUser(postController.App, username, password, createdAt, updatedAt)
|
||||
_, err := models.CreateUser(p.App, username, password, createdAt, updatedAt)
|
||||
if err != nil {
|
||||
log.Println("Error creating user")
|
||||
log.Println(err)
|
@ -8,8 +8,8 @@ import (
|
||||
"log"
|
||||
)
|
||||
|
||||
// ConnectDB returns a new database connection
|
||||
func ConnectDB(app *app.App) *sql.DB {
|
||||
// Connect returns a new database connection
|
||||
func Connect(app *app.App) *sql.DB {
|
||||
// Set connection parameters from config
|
||||
postgresConfig := fmt.Sprintf("host=%s port=%s user=%s "+
|
||||
"password=%s dbname=%s sslmode=disable",
|
@ -36,7 +36,6 @@ func Migrate(app *app.App, anyStruct interface{}) error {
|
||||
|
||||
// createTable creates a table with the given name if it doesn't exist, it is assumed that id will be the primary key
|
||||
func createTable(app *app.App, tableName string) error {
|
||||
// Check to see if the table already exists
|
||||
var tableExists bool
|
||||
err := app.Db.QueryRow("SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relname ~ $1 AND pg_catalog.pg_table_is_visible(c.oid))", "^"+tableName+"$").Scan(&tableExists)
|
||||
if err != nil {
|
||||
@ -63,7 +62,6 @@ func createTable(app *app.App, tableName string) error {
|
||||
|
||||
// createColumn creates a column with the given name and type if it doesn't exist
|
||||
func createColumn(app *app.App, tableName, columnName, columnType string) error {
|
||||
// Check to see if the column already exists
|
||||
var columnExists bool
|
||||
err := app.Db.QueryRow("SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = $1 AND column_name = $2)", tableName, columnName).Scan(&columnExists)
|
||||
if err != nil {
|
||||
|
4
go.mod
4
go.mod
@ -3,6 +3,6 @@ module GoWeb
|
||||
go 1.20
|
||||
|
||||
require (
|
||||
github.com/lib/pq v1.10.7
|
||||
golang.org/x/crypto v0.7.0
|
||||
github.com/lib/pq v1.10.9
|
||||
golang.org/x/crypto v0.11.0
|
||||
)
|
||||
|
8
go.sum
8
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.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A=
|
||||
golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA=
|
||||
golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio=
|
||||
|
7
main.go
7
main.go
@ -44,7 +44,7 @@ func main() {
|
||||
log.SetOutput(file)
|
||||
|
||||
// Connect to database and run migrations
|
||||
appLoaded.Db = database.ConnectDB(&appLoaded)
|
||||
appLoaded.Db = database.Connect(&appLoaded)
|
||||
if appLoaded.Config.Db.AutoMigrate {
|
||||
err = models.RunAllMigrations(&appLoaded)
|
||||
if err != nil {
|
||||
@ -60,8 +60,8 @@ func main() {
|
||||
}
|
||||
|
||||
// Define Routes
|
||||
routes.GetRoutes(&appLoaded)
|
||||
routes.PostRoutes(&appLoaded)
|
||||
routes.Get(&appLoaded)
|
||||
routes.Post(&appLoaded)
|
||||
|
||||
// Start server
|
||||
server := &http.Server{Addr: appLoaded.Config.Listen.Ip + ":" + appLoaded.Config.Listen.Port}
|
||||
@ -78,6 +78,7 @@ func main() {
|
||||
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...")
|
||||
|
||||
|
21
middleware/csrf.go
Normal file
21
middleware/csrf.go
Normal file
@ -0,0 +1,21 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"GoWeb/security"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Csrf validates the CSRF token and returns the handler function if it succeded
|
||||
func Csrf(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
_, err := security.VerifyCsrfToken(r)
|
||||
if err != nil {
|
||||
log.Println("Error verifying csrf token")
|
||||
http.Error(w, "Forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
f(w, r)
|
||||
}
|
||||
}
|
5
middleware/groups.go
Normal file
5
middleware/groups.go
Normal file
@ -0,0 +1,5 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
type MiddlewareFunc func(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request)
|
14
middleware/wrapper.go
Normal file
14
middleware/wrapper.go
Normal file
@ -0,0 +1,14 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
// ProcessGroup is a wrapper function for the http.HandleFunc function
|
||||
// that takes the function you want to execute (f) and the middleware you want
|
||||
// to execute (m) this should be used when processing multiple groups of middleware at a time
|
||||
func ProcessGroup(f func(w http.ResponseWriter, r *http.Request), m []MiddlewareFunc) func(w http.ResponseWriter, r *http.Request) {
|
||||
for _, middleware := range m {
|
||||
_ = middleware(f)
|
||||
}
|
||||
|
||||
return f
|
||||
}
|
@ -64,16 +64,26 @@ func CreateSession(app *app.App, w http.ResponseWriter, userId int64, remember b
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func GetSessionByAuthToken(app *app.App, authToken string) (Session, error) {
|
||||
session := Session{}
|
||||
|
||||
err := app.Db.QueryRow(selectSessionByAuthToken, authToken).Scan(&session.Id, &session.UserId, &session.AuthToken, &session.RememberMe, &session.CreatedAt)
|
||||
if err != nil {
|
||||
log.Println("Error getting session by auth token")
|
||||
return Session{}, err
|
||||
}
|
||||
|
||||
return session, nil
|
||||
}
|
||||
|
||||
// Generates a random 64-byte string
|
||||
func generateAuthToken(app *app.App) string {
|
||||
// Generate random bytes
|
||||
b := make([]byte, 64)
|
||||
_, err := rand.Read(b)
|
||||
if err != nil {
|
||||
log.Println("Error generating random bytes")
|
||||
}
|
||||
|
||||
// Convert random bytes to hex string
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
@ -117,7 +127,6 @@ func deleteSessionCookie(app *app.App, w http.ResponseWriter) {
|
||||
|
||||
// DeleteSessionByAuthToken deletes a session from the database by AuthToken
|
||||
func DeleteSessionByAuthToken(app *app.App, w http.ResponseWriter, authToken string) error {
|
||||
// Delete session from database
|
||||
_, err := app.Db.Exec(deleteSessionByAuthToken, authToken)
|
||||
if err != nil {
|
||||
log.Println("Error deleting session from database")
|
||||
|
@ -23,10 +23,9 @@ const userColumns = "\"Id\", " + userColumnsNoId
|
||||
const userTable = "public.\"User\""
|
||||
|
||||
const (
|
||||
selectSessionIdByAuthToken = "SELECT \"Id\" FROM public.\"Session\" WHERE \"AuthToken\" = $1"
|
||||
selectUserById = "SELECT " + userColumns + " FROM " + userTable + " WHERE \"Id\" = $1"
|
||||
selectUserByUsername = "SELECT " + userColumns + " FROM " + userTable + " WHERE \"Username\" = $1"
|
||||
insertUser = "INSERT INTO " + userTable + " (" + userColumnsNoId + ") VALUES ($1, $2, $3, $4) RETURNING \"Id\""
|
||||
selectUserById = "SELECT " + userColumns + " FROM " + userTable + " WHERE \"Id\" = $1"
|
||||
selectUserByUsername = "SELECT " + userColumns + " FROM " + userTable + " WHERE \"Username\" = $1"
|
||||
insertUser = "INSERT INTO " + userTable + " (" + userColumnsNoId + ") VALUES ($1, $2, $3, $4) RETURNING \"Id\""
|
||||
)
|
||||
|
||||
// GetCurrentUser finds the currently logged-in user by session cookie
|
||||
@ -37,23 +36,19 @@ func GetCurrentUser(app *app.App, r *http.Request) (User, error) {
|
||||
return User{}, err
|
||||
}
|
||||
|
||||
var userId int64
|
||||
|
||||
// Query row by AuthToken
|
||||
err = app.Db.QueryRow(selectSessionIdByAuthToken, cookie.Value).Scan(&userId)
|
||||
session, err := GetSessionByAuthToken(app, cookie.Value)
|
||||
if err != nil {
|
||||
log.Println("Error querying session row with session: " + cookie.Value)
|
||||
log.Println("Error getting session by auth token")
|
||||
return User{}, err
|
||||
}
|
||||
|
||||
return GetUserById(app, userId)
|
||||
return GetUserById(app, session.UserId)
|
||||
}
|
||||
|
||||
// GetUserById finds a User table row in the database by id and returns a struct representing this row
|
||||
func GetUserById(app *app.App, id int64) (User, error) {
|
||||
user := User{}
|
||||
|
||||
// Query row by id
|
||||
err := app.Db.QueryRow(selectUserById, id).Scan(&user.Id, &user.Username, &user.Password, &user.CreatedAt, &user.UpdatedAt)
|
||||
if err != nil {
|
||||
log.Println("Get user error (user not found) for user id:" + strconv.FormatInt(id, 10))
|
||||
@ -67,7 +62,6 @@ func GetUserById(app *app.App, id int64) (User, error) {
|
||||
func GetUserByUsername(app *app.App, username string) (User, error) {
|
||||
user := User{}
|
||||
|
||||
// Query row by username
|
||||
err := app.Db.QueryRow(selectUserByUsername, username).Scan(&user.Id, &user.Username, &user.Password, &user.CreatedAt, &user.UpdatedAt)
|
||||
if err != nil {
|
||||
log.Println("Get user error (user not found) for user:" + username)
|
||||
@ -79,7 +73,6 @@ func GetUserByUsername(app *app.App, username string) (User, error) {
|
||||
|
||||
// CreateUser creates a User table row in the database
|
||||
func CreateUser(app *app.App, username string, password string, createdAt time.Time, updatedAt time.Time) (User, error) {
|
||||
// Hash password
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
log.Println("Error hashing password when creating user")
|
||||
@ -101,14 +94,12 @@ func CreateUser(app *app.App, username string, password string, createdAt time.T
|
||||
func AuthenticateUser(app *app.App, w http.ResponseWriter, username string, password string, remember bool) (Session, error) {
|
||||
var user User
|
||||
|
||||
// Query row by username
|
||||
err := app.Db.QueryRow(selectUserByUsername, username).Scan(&user.Id, &user.Username, &user.Password, &user.CreatedAt, &user.UpdatedAt)
|
||||
if err != nil {
|
||||
log.Println("Authentication error (user not found) for user:" + username)
|
||||
return Session{}, err
|
||||
}
|
||||
|
||||
// Validate password
|
||||
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
|
||||
if err != nil { // Failed to validate password, doesn't match
|
||||
log.Println("Authentication error (incorrect password) for user:" + username)
|
||||
@ -120,14 +111,12 @@ func AuthenticateUser(app *app.App, w http.ResponseWriter, username string, pass
|
||||
|
||||
// LogoutUser deletes the session cookie and AuthToken from the database
|
||||
func LogoutUser(app *app.App, w http.ResponseWriter, r *http.Request) {
|
||||
// Get cookie from request
|
||||
cookie, err := r.Cookie("session")
|
||||
if err != nil {
|
||||
log.Println("Error getting cookie from request")
|
||||
return
|
||||
}
|
||||
|
||||
// Set token to empty string
|
||||
err = DeleteSessionByAuthToken(app, w, cookie.Value)
|
||||
if err != nil {
|
||||
log.Println("Error deleting session by AuthToken")
|
||||
|
57
restclient/client.go
Normal file
57
restclient/client.go
Normal file
@ -0,0 +1,57 @@
|
||||
package restclient
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// SendRequest sends an HTTP request to a URL and includes the specified headers and body.
|
||||
// A body can be nil for GET requests, a map[string]string for multipart/form-data requests,
|
||||
// or a struct for JSON requests
|
||||
func SendRequest(url string, method string, headers map[string]string, body interface{}) (http.Response, error) {
|
||||
var reqBody *bytes.Buffer
|
||||
var contentType string
|
||||
|
||||
switch v := body.(type) {
|
||||
case nil:
|
||||
reqBody = bytes.NewBuffer([]byte(""))
|
||||
case map[string]string:
|
||||
reqBody = &bytes.Buffer{}
|
||||
writer := multipart.NewWriter(reqBody)
|
||||
for key, value := range v {
|
||||
writer.WriteField(key, value)
|
||||
}
|
||||
writer.Close()
|
||||
contentType = writer.FormDataContentType()
|
||||
default:
|
||||
jsonBody, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return http.Response{}, err
|
||||
}
|
||||
reqBody = bytes.NewBuffer(jsonBody)
|
||||
contentType = "application/json"
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(method, url, reqBody)
|
||||
if err != nil {
|
||||
return http.Response{}, err
|
||||
}
|
||||
|
||||
if contentType != "" {
|
||||
req.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
|
||||
for key, value := range headers {
|
||||
req.Header.Add(key, value)
|
||||
}
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return http.Response{}, err
|
||||
}
|
||||
|
||||
return *resp, nil
|
||||
}
|
@ -8,10 +8,10 @@ import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// GetRoutes defines all project get routes
|
||||
func GetRoutes(app *app.App) {
|
||||
// Get defines all project get routes
|
||||
func Get(app *app.App) {
|
||||
// Get controller struct initialize
|
||||
getController := controllers.GetController{
|
||||
getController := controllers.Get{
|
||||
App: app,
|
||||
}
|
||||
|
20
routes/post.go
Normal file
20
routes/post.go
Normal file
@ -0,0 +1,20 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"GoWeb/app"
|
||||
"GoWeb/controllers"
|
||||
"GoWeb/middleware"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Post defines all project post routes
|
||||
func Post(app *app.App) {
|
||||
// Post controller struct initialize
|
||||
postController := controllers.Post{
|
||||
App: app,
|
||||
}
|
||||
|
||||
// User authentication
|
||||
http.HandleFunc("/register-handle", middleware.Csrf(postController.Register))
|
||||
http.HandleFunc("/login-handle", middleware.Csrf(postController.Login))
|
||||
}
|
@ -1,19 +0,0 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"GoWeb/app"
|
||||
"GoWeb/controllers"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// PostRoutes defines all project post routes
|
||||
func PostRoutes(app *app.App) {
|
||||
// Post controller struct initialize
|
||||
postController := controllers.PostController{
|
||||
App: app,
|
||||
}
|
||||
|
||||
// User authentication
|
||||
http.HandleFunc("/register-handle", postController.Register)
|
||||
http.HandleFunc("/login-handle", postController.Login)
|
||||
}
|
@ -10,7 +10,6 @@ import (
|
||||
|
||||
// GenerateCsrfToken generates a csrf token and assigns it to a cookie for double submit cookie csrf protection
|
||||
func GenerateCsrfToken(w http.ResponseWriter, _ *http.Request) (string, error) {
|
||||
// Generate random 64 character string (alpha-numeric)
|
||||
buff := make([]byte, int(math.Ceil(float64(64)/2)))
|
||||
_, err := rand.Read(buff)
|
||||
if err != nil {
|
||||
|
Reference in New Issue
Block a user