From 34b58fd834d9db112fe19f38a22703aa76db60d0 Mon Sep 17 00:00:00 2001 From: Hamza Ali Date: Wed, 5 Feb 2020 11:55:03 +0700 Subject: [PATCH] go: add config file via struct --- common/structs.go | 23 ++++++++++++++ db/connection.go | 5 +-- main.go | 19 +++++++----- server/server.go | 6 ++-- server/socket/hub.go | 9 ++++-- server/socket/mail.go | 69 ------------------------------------------ server/socket/redis.go | 5 ++- 7 files changed, 50 insertions(+), 86 deletions(-) delete mode 100644 server/socket/mail.go diff --git a/common/structs.go b/common/structs.go index 0cb0932..9675990 100644 --- a/common/structs.go +++ b/common/structs.go @@ -27,3 +27,26 @@ type Ticket struct { Start time.Time `json:"start"` End time.Time `json:"end"` } + +//Config Struct represents the structure that holds the entire app config +type Configuration struct { + Debug bool + IP int + Database string + Server struct { + SSL bool + CertFile string + KeyFile string + Port int + } + Redis struct { + Addr string + Channel string + } + Mail struct { + Host string + Port int + Username string + Logo string + } +} diff --git a/db/connection.go b/db/connection.go index 9ebc235..8b32c08 100644 --- a/db/connection.go +++ b/db/connection.go @@ -1,6 +1,7 @@ package db import ( + "JISQueueing/common" "database/sql" // Import the SQLite library we're going to use so SQL can use it. @@ -10,8 +11,8 @@ import ( var db *sql.DB var alreadyUsingMemory bool -func init() { - openDatabase("./database.sqlite") +func Init_DB(config common.Configuration) { + openDatabase(config.Database) } func openDatabase(fileLocation string) { diff --git a/main.go b/main.go index bab6c90..2b56ba9 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,8 @@ package main import ( + "JISQueueing/common" + "JISQueueing/db" "JISQueueing/server" "fmt" "github.com/spf13/viper" @@ -19,6 +21,7 @@ func main() { viper.SetDefault("debug", false) viper.SetDefault("ip", "10.1.3.100") + viper.SetDefault("database", "/etc/queuing/database.sqlite") viper.SetDefault("server.ssl", true) viper.SetDefault("server.certFile", "/etc/queuing/server.crt") viper.SetDefault("server.keyFile", "/etc/queuing/server.key") @@ -30,26 +33,28 @@ func main() { viper.SetDefault("mail.username", "IT.Q@jisedu.or.id") viper.SetDefault("mail.logo", "/etc/queuing/logo.jpg") - err := viper.ReadInConfig() + var config common.Configuration + err := viper.Unmarshal(&config) if err != nil { if _, ok := err.(viper.ConfigFileNotFoundError); !ok { panic(fmt.Errorf("Fatal error config file: %s \n", err)) } } - hostLocation := ":" + strconv.Itoa(viper.GetInt("port")) - mux := server.NewServerMux() + db.Init_DB(config) + hostLocation := ":" + strconv.Itoa(config.Server.Port) + mux := server.NewServerMux(config) cors := handlers.CORS( handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"}), handlers.AllowedMethods([]string{"POST", "OPTIONS"}), handlers.AllowedOrigins([]string{"*"}), )(mux) - if viper.GetBool("server.ssl") { - crt := viper.GetString("server.certFile") - key := viper.GetString("server.keyFile") + if config.Server.SSL { + crt := config.Server.CertFile + key := config.Server.KeyFile log.Fatal(http.ListenAndServeTLS(hostLocation, crt, key, cors)) } else { log.Fatal(http.ListenAndServe(hostLocation, cors)) } -} +} \ No newline at end of file diff --git a/server/server.go b/server/server.go index 0614428..bc5e6a4 100644 --- a/server/server.go +++ b/server/server.go @@ -1,6 +1,7 @@ package server import ( + "JISQueueing/common" "JISQueueing/server/socket" "net/http" @@ -8,7 +9,7 @@ import ( ) //NewServerMux creates a new http handler object handling API requests -func NewServerMux() http.Handler { +func NewServerMux(config common.Configuration) http.Handler { router := mux.NewRouter() router.NotFoundHandler = http.HandlerFunc(NotFound) @@ -26,7 +27,8 @@ func NewServerMux() http.Handler { router.PathPrefix("/static").Handler(http.FileServer(http.Dir("./static"))) router.PathPrefix("/").HandlerFunc(indexHandler) - socket.StartRedisServer() + socket.StartRedisServer(config) + socket.SetConfiguration(config) return router } diff --git a/server/socket/hub.go b/server/socket/hub.go index a976196..c00e2ab 100644 --- a/server/socket/hub.go +++ b/server/socket/hub.go @@ -10,6 +10,11 @@ import ( ) var queue = make([]common.Ticket, 0) +var config common.Configuration + +func SetConfiguration(configFile common.Configuration) { + config = configFile +} func newTicket(ticket common.Ticket, who *websocket.Conn) { queue = append(queue, ticket) @@ -50,10 +55,8 @@ func finishedTicket(id int, table int, who *websocket.Conn) { } who.WriteMessage(websocket.TextMessage, []byte("success complete "+strconv.Itoa(id))) notifyTicket(who) - ticket, _ := db.GetTicket(id) + //ticket, _ := db.GetTicket(id) sendDisplayMessage("complete " + strconv.Itoa(table)) - sendThankYouEmail(ticket) - } func cancelTicket(id int, table int, who *websocket.Conn) { diff --git a/server/socket/mail.go b/server/socket/mail.go deleted file mode 100644 index 11ed7a4..0000000 --- a/server/socket/mail.go +++ /dev/null @@ -1,69 +0,0 @@ -package socket - -import ( - "JISQueueing/common" - "bytes" - "encoding/base64" - "html/template" - "net/smtp" - "strings" -) - -var ( - bodyT = `` - t, _ = template.New("email").Parse(bodyT) -) - -func sendThankYouEmail(ticket common.Ticket) { - buffer := new(bytes.Buffer) - t.Execute(buffer, ticket) - body := buffer.String() - SendMail( - "mail1.jisedu.or.id:25", - "IT.Q@jisedu.or.id", - "Thank you for coming to the JIS IT Helpdesk", - body, - []string{ticket.Email}, - ) -} - -func SendMail(addr, from, subject, body string, to []string) error { - r := strings.NewReplacer("\r\n", "", "\r", "", "\n", "", "%0a", "", "%0d", "") - - c, err := smtp.Dial(addr) - if err != nil { - return err - } - defer c.Close() - if err = c.Mail(r.Replace(from)); err != nil { - return err - } - for i := range to { - to[i] = r.Replace(to[i]) - if err = c.Rcpt(to[i]); err != nil { - return err - } - } - - w, err := c.Data() - if err != nil { - return err - } - - msg := "To: " + strings.Join(to, ",") + "\r\n" + - "From: " + from + "\r\n" + - "Subject: " + subject + "\r\n" + - "Content-Type: text/html; charset=\"UTF-8\"\r\n" + - "Content-Transfer-Encoding: base64\r\n" + - "\r\n" + base64.StdEncoding.EncodeToString([]byte(body)) - - _, err = w.Write([]byte(msg)) - if err != nil { - return err - } - err = w.Close() - if err != nil { - return err - } - return c.Quit() -} diff --git a/server/socket/redis.go b/server/socket/redis.go index a180e95..d9b3fe0 100644 --- a/server/socket/redis.go +++ b/server/socket/redis.go @@ -3,7 +3,6 @@ package socket import ( json "encoding/json" "github.com/go-redis/redis/v7" - "github.com/spf13/viper" ) var client *redis.Client @@ -17,7 +16,7 @@ type Message struct { func StartRedisServer() { client = redis.NewClient(&redis.Options{ - Addr: viper.GetString("redis.addr"), + Addr: config.Redis.Addr, }) _, err := client.Ping().Result() @@ -34,7 +33,7 @@ func StartRedisServer() { func sendMessageToRedisChannel(msg Message) { mesg, _ := json.Marshal(msg) - status := client.Publish(viper.GetString("viper.channel"), string(mesg)) + status := client.Publish(config.Redis.Channel, string(mesg)) if status.Err() != nil { println("Error while sending message to redis:", status.Err().Error()) }