Compare commits
4 Commits
v1.5.0
...
file_uploa
Author | SHA1 | Date | |
---|---|---|---|
37391190fb | |||
1fb8fdef81 | |||
baef0cbe78 | |||
d0da1a9114 |
@ -12,9 +12,7 @@ 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
|
||||
|
@ -25,6 +25,11 @@ type Configuration struct {
|
||||
Template struct {
|
||||
BaseName string `json:"BaseTemplateName"`
|
||||
}
|
||||
|
||||
Upload struct {
|
||||
BaseName string `json:"UploadDirectoryName"`
|
||||
MaxSize int64 `json:"MaxUploadSize"`
|
||||
}
|
||||
}
|
||||
|
||||
// LoadConfig loads and returns a configuration struct
|
||||
|
@ -61,6 +61,13 @@ func (getController *GetController) ShowLogin(w http.ResponseWriter, r *http.Req
|
||||
templating.RenderTemplate(getController.App, w, "templates/pages/login.html", data)
|
||||
}
|
||||
|
||||
func (getController *GetController) ShowFile(w http.ResponseWriter, r *http.Request) {
|
||||
// GET /uploads?name=file.jpg
|
||||
// will serve file.jpg
|
||||
name := r.URL.Query().Get("name")
|
||||
http.ServeFile(w, r, getController.App.Config.Upload.BaseName+name)
|
||||
}
|
||||
|
||||
func (getController *GetController) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
models.LogoutUser(getController.App, w, r)
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
|
@ -3,8 +3,12 @@ package controllers
|
||||
import (
|
||||
"GoWeb/app"
|
||||
"GoWeb/models"
|
||||
"GoWeb/security"
|
||||
"io"
|
||||
"log"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
@ -14,6 +18,13 @@ type PostController struct {
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
username := r.FormValue("username")
|
||||
password := r.FormValue("password")
|
||||
remember := r.FormValue("remember") == "on"
|
||||
@ -23,7 +34,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(postController.App, w, username, password, remember)
|
||||
if err != nil {
|
||||
log.Println("Error authenticating user")
|
||||
log.Println(err)
|
||||
@ -35,6 +46,13 @@ func (postController *PostController) Login(w http.ResponseWriter, r *http.Reque
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
username := r.FormValue("username")
|
||||
password := r.FormValue("password")
|
||||
createdAt := time.Now()
|
||||
@ -45,7 +63,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(postController.App, username, password, createdAt, updatedAt)
|
||||
if err != nil {
|
||||
log.Println("Error creating user")
|
||||
log.Println(err)
|
||||
@ -54,3 +72,60 @@ func (postController *PostController) Register(w http.ResponseWriter, r *http.Re
|
||||
|
||||
http.Redirect(w, r, "/login", http.StatusFound)
|
||||
}
|
||||
|
||||
func (postController *PostController) FileUpload(w http.ResponseWriter, r *http.Request) {
|
||||
max := postController.App.Config.Upload.MaxSize
|
||||
err := r.ParseMultipartForm(max)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// FormFile returns the first file for the given key `file`
|
||||
// it also returns the FileHeader, so we can get the Filename,
|
||||
// the Header and the size of the file
|
||||
file, handler, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
log.Println("Error Retrieving the File")
|
||||
log.Println(err)
|
||||
return
|
||||
}
|
||||
defer func(file multipart.File) {
|
||||
err := file.Close()
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
}(file)
|
||||
|
||||
if handler.Size > max {
|
||||
log.Println("User tried uploading a file which is too large.")
|
||||
http.Redirect(w, r, "/", http.StatusRequestHeaderFieldsTooLarge)
|
||||
return
|
||||
}
|
||||
|
||||
// Create a temporary file within upload directory
|
||||
tempFile, err := os.Create(postController.App.Config.Upload.BaseName + handler.Filename)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
http.Redirect(w, r, "/", http.StatusNotAcceptable)
|
||||
}
|
||||
defer func(tempFile *os.File) {
|
||||
err := tempFile.Close()
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
}(tempFile)
|
||||
|
||||
// read all the contents of our uploaded file into a
|
||||
// byte array
|
||||
fileBytes, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
|
||||
_, err = tempFile.Write(fileBytes)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
}
|
||||
|
@ -13,5 +13,9 @@
|
||||
},
|
||||
"Template": {
|
||||
"BaseTemplateName": "templates/base.html"
|
||||
},
|
||||
"Upload": {
|
||||
"UploadDirectoryName": "goweb-uploads/",
|
||||
"MaxUploadSize": 10485760
|
||||
}
|
||||
}
|
||||
}
|
||||
|
2
go.mod
2
go.mod
@ -4,5 +4,5 @@ go 1.20
|
||||
|
||||
require (
|
||||
github.com/lib/pq v1.10.9
|
||||
golang.org/x/crypto v0.11.0
|
||||
golang.org/x/crypto v0.8.0
|
||||
)
|
||||
|
4
go.sum
4
go.sum
@ -1,4 +1,4 @@
|
||||
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=
|
||||
golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ=
|
||||
golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE=
|
||||
|
9
main.go
9
main.go
@ -8,6 +8,7 @@ import (
|
||||
"GoWeb/routes"
|
||||
"context"
|
||||
"embed"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
@ -43,6 +44,14 @@ func main() {
|
||||
file, err := os.OpenFile("logs/"+time.Now().Format("2006-01-02")+".log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
|
||||
log.SetOutput(file)
|
||||
|
||||
// Create upload directory if it doesn't exist
|
||||
uploadPath := appLoaded.Config.Upload.BaseName
|
||||
if _, err := os.Stat(uploadPath); errors.Is(err, os.ErrNotExist) {
|
||||
if err := os.MkdirAll(uploadPath, os.ModePerm); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Connect to database and run migrations
|
||||
appLoaded.Db = database.ConnectDB(&appLoaded)
|
||||
if appLoaded.Config.Db.AutoMigrate {
|
||||
|
@ -1,22 +0,0 @@
|
||||
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) {
|
||||
// Verify csrf token
|
||||
_, err := security.VerifyCsrfToken(r)
|
||||
if err != nil {
|
||||
log.Println("Error verifying csrf token")
|
||||
http.Error(w, "Forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
f(w, r)
|
||||
}
|
||||
}
|
@ -1,5 +0,0 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
type MiddlewareFunc func(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request)
|
@ -1,14 +0,0 @@
|
||||
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
|
||||
}
|
@ -1,57 +0,0 @@
|
||||
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
|
||||
}
|
@ -30,4 +30,7 @@ func GetRoutes(app *app.App) {
|
||||
http.HandleFunc("/login", getController.ShowLogin)
|
||||
http.HandleFunc("/register", getController.ShowRegister)
|
||||
http.HandleFunc("/logout", getController.Logout)
|
||||
|
||||
// Files
|
||||
http.HandleFunc("/uploads", getController.ShowFile)
|
||||
}
|
||||
|
@ -3,7 +3,6 @@ package routes
|
||||
import (
|
||||
"GoWeb/app"
|
||||
"GoWeb/controllers"
|
||||
"GoWeb/middleware"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
@ -15,6 +14,7 @@ func PostRoutes(app *app.App) {
|
||||
}
|
||||
|
||||
// User authentication
|
||||
http.HandleFunc("/register-handle", middleware.Csrf(postController.Register))
|
||||
http.HandleFunc("/login-handle", middleware.Csrf(postController.Login))
|
||||
http.HandleFunc("/register-handle", postController.Register)
|
||||
http.HandleFunc("/login-handle", postController.Login)
|
||||
http.HandleFunc("/upload-handle", postController.FileUpload)
|
||||
}
|
||||
|
@ -1,5 +1,25 @@
|
||||
{{ define "pageTitle" }}Home{{ end }}
|
||||
|
||||
{{ define "file-upload" }}
|
||||
<form
|
||||
enctype="multipart/form-data"
|
||||
action="/upload-handle"
|
||||
method="post"
|
||||
>
|
||||
<input type="file" accept="*/*" name="file" />
|
||||
<input type="submit" value="upload" />
|
||||
</form>
|
||||
{{ end }}
|
||||
|
||||
{{ define "content" }}
|
||||
{{ .Test }}
|
||||
{{ end }}
|
||||
|
||||
<!-- Uncomment below to demo file upload system -->
|
||||
|
||||
<!-- {{ template "file-upload" . }} -->
|
||||
<!-- <p>Upload an image called test.jpg to test the file upload system</p> -->
|
||||
<!-- <img src="/uploads?name=test.jpg" alt=""> -->
|
||||
{{ end }}
|
||||
|
||||
{{ define "content" }}
|
||||
{{ end }}
|
||||
|
Reference in New Issue
Block a user