Refactoring

This commit is contained in:
2024-06-06 14:07:16 +01:00
parent a86223391b
commit 77c2c9a8b8
10 changed files with 137 additions and 115 deletions
+2 -1
View File
@@ -1,8 +1,10 @@
FROM alpine:20231219
# Set the appropriate timezone
ENV TZ="Europe/Lisbon"
# Install the required packages
RUN apk --no-cache add bash zsh go make sqlite \
&& rm -rf /tmp/*
@@ -13,7 +15,6 @@ COPY ./src /frontend-src
# Add the entrypoint
USER $UNAME
COPY ./container/start.sh /start.sh
STOPSIGNAL SIGTERM
ENTRYPOINT [ "/start.sh" ]
+1
View File
@@ -1 +1,2 @@
build/
data.db
+51
View File
@@ -0,0 +1,51 @@
/*
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
*/
package cmd
import (
"os"
"thermalFax/config"
"thermalFax/server"
"github.com/spf13/cobra"
)
func rootCmdAction(cmd *cobra.Command, args []string) {
cfgPath, _ := cmd.Flags().GetString("config")
// Initialize configuration
// This runs a sync.Once
config.GetInstance(cfgPath, nil)
server.Server()
}
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "thermalPrinter",
Short: "",
Long: ``,
Run: rootCmdAction,
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}
func init() {
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
/* rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.thermalPrinter.yaml)") */
// Cobra also supports local flags, which will only run
// when this action is called directly.
/* rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") */
rootCmd.Flags().StringP("config", "c", "", "Config file path")
}
+13 -19
View File
@@ -38,27 +38,20 @@ type Configuration struct {
}
func findConfigFile() (string, error) {
log.Println("Trying XDG path")
XDGPATH := "~/.config/fax/config.yml"
if _, err := os.Stat(XDGPATH); err == nil {
log.Println("Found XDG config file.")
return XDGPATH, nil
configLocations := map[string]string{
"XDG": "~/.config/fax/config.yml",
"RUNTIME": "~/.config.yml",
"ETC": "/etc/fax/config.yml",
}
log.Println("Trying RUNTIME path")
RUNTIMEPATH := "./config.yml"
if _, err := os.Stat(RUNTIMEPATH); err == nil {
log.Println("Found runtime config file.")
return RUNTIMEPATH, nil
}
log.Println("Trying ETC path")
ETCPATH := "/etc/fax/config.yml"
if _, err := os.Stat(ETCPATH); err == nil {
log.Println("Found etc config file.")
return ETCPATH, nil
for name, path := range configLocations {
if _, err := os.Stat(path); err == nil {
log.Printf("Found %s config file\n", name)
return path, nil
}
}
log.Println("No default config file found.")
return "", errors.New("could not find viable config file")
}
@@ -67,10 +60,12 @@ func GetInstance(path string, data []byte) *Configuration {
instance = &Configuration{}
if path == "" {
log.Println("No configuration file provided... Searching in default locations")
var err error
path, err = findConfigFile()
if err != nil {
log.Fatal("Could not find a configuration file.")
log.Fatal("Could not find a configuration file. Terminating")
// We could print the correct places to add a configuration file here
}
}
@@ -82,7 +77,6 @@ func GetInstance(path string, data []byte) *Configuration {
}
func (c *Configuration) loadConfiguration(data []byte) {
// Instead of opening this file we should be trying other paths first
var file []byte
if data != nil {
file = data
+6 -1
View File
@@ -4,8 +4,13 @@ go 1.22.2
require (
github.com/golang-jwt/jwt/v4 v4.5.0
github.com/google/go-cmp v0.6.0
github.com/mattn/go-sqlite3 v1.14.22
github.com/spf13/cobra v1.8.0
golang.org/x/crypto v0.22.0
gopkg.in/yaml.v2 v2.4.0
)
require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
)
+9 -2
View File
@@ -1,12 +1,19 @@
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg=
github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30=
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+7 -46
View File
@@ -1,53 +1,14 @@
package main
import (
"fmt"
"log"
"net/http"
"thermalFax/config"
"thermalFax/controllers"
"thermalFax/cmd"
)
func checkMethod(method string, r *http.Request) bool {
return r.Method == method
}
/*
This works by calling the root command of cobra-cli.
That will handle the command-line flags we might want to pass.
On that root command we will do the initial setups and then launch the server.
*/
func main() {
// Initialize configuration
_ = config.GetInstance("", nil)
// GET calls
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if !checkMethod(http.MethodGet, r) {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
controllers.EditorPage(w, r)
})
// POST calls
http.HandleFunc("/send-fax", func(w http.ResponseWriter, r *http.Request) {
if !checkMethod(http.MethodPost, r) {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
controllers.SendFax(w, r)
})
http.HandleFunc("/send-login", func(w http.ResponseWriter, r *http.Request) {
if !checkMethod(http.MethodPost, r) {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
controllers.Authenticate(w, r)
})
// Serve the CSS and JS files, we might have to change this
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))
fmt.Println("Starting server on port 8083")
log.Fatal(http.ListenAndServe(":8083", nil))
cmd.Execute()
}
-37
View File
@@ -1,37 +0,0 @@
package models
// This isn't used anymore, will keep it here for a while, for reasons, its mine
// pass -> $2y$08$ZBb/RxlrNHcA.YNasvGlhOeUmJVZe/clNelP4jwBpkpq/r4mE.lze
// func (a *Authentication) isAuthorised(user string, pass string) bool {
// p, ok := DATABASE[user]
// if !ok {
// return false
// }
// err := bcrypt.CompareHashAndPassword([]byte(p), []byte(pass))
// return err == nil
// }
// func (a *Authentication) Authenticate(w http.ResponseWriter, r *http.Request) bool {
// username, password, ok := r.BasicAuth()
// if !ok {
// log.Println("Log in failed")
// w.Header().Add("WWW-Authenticate", `Basic realm="Give username and password"`)
// w.WriteHeader(http.StatusUnauthorized)
// w.Write([]byte(`{"message": "No basic auth present"}`))
// return false
// }
// if !a.isAuthorised(username, password) {
// log.Printf("Log in failed: %s:%s", username, password)
// w.Header().Add("WWW-Authenticate", `Basic realm="Give username and password"`)
// w.WriteHeader(http.StatusUnauthorized)
// w.Write([]byte(`{"message": "Invalid username or password"}`))
// return false
// }
// log.Printf("User %s logged in successfully", username)
// return true
// }
-9
View File
@@ -6,15 +6,6 @@ import (
_ "github.com/mattn/go-sqlite3"
)
type DBAccess interface {
// I should make a query struct so that I can make generic structs
// And then slap them into different types of DBs
createq(query string) error
selectq(query string) error
deleteq(query string) error
updateq(query string) error
}
type Database struct {
DB *sql.DB
Path string
+48
View File
@@ -0,0 +1,48 @@
package server
import (
"log"
"net/http"
"thermalFax/controllers"
)
func checkMethod(method string, r *http.Request) bool {
return r.Method == method
}
func Server() {
// GET calls
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if !checkMethod(http.MethodGet, r) {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
controllers.EditorPage(w, r)
})
// POST calls
http.HandleFunc("/send-fax", func(w http.ResponseWriter, r *http.Request) {
if !checkMethod(http.MethodPost, r) {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
controllers.SendFax(w, r)
})
http.HandleFunc("/send-login", func(w http.ResponseWriter, r *http.Request) {
if !checkMethod(http.MethodPost, r) {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
controllers.Authenticate(w, r)
})
// Serve the CSS and JS files, we might have to change this
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))
log.Println("Starting server on port 8083")
log.Fatal(http.ListenAndServe(":8083", nil))
}