go: add config file via struct

websocket
ALI Hamza 2020-02-05 11:55:03 +07:00
parent 89606b390a
commit 34b58fd834
No known key found for this signature in database
GPG Key ID: BCA8A46C87798C4C
7 changed files with 50 additions and 86 deletions

@ -27,3 +27,26 @@ type Ticket struct {
Start time.Time `json:"start"` Start time.Time `json:"start"`
End time.Time `json:"end"` 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
}
}

@ -1,6 +1,7 @@
package db package db
import ( import (
"JISQueueing/common"
"database/sql" "database/sql"
// Import the SQLite library we're going to use so SQL can use it. // Import the SQLite library we're going to use so SQL can use it.
@ -10,8 +11,8 @@ import (
var db *sql.DB var db *sql.DB
var alreadyUsingMemory bool var alreadyUsingMemory bool
func init() { func Init_DB(config common.Configuration) {
openDatabase("./database.sqlite") openDatabase(config.Database)
} }
func openDatabase(fileLocation string) { func openDatabase(fileLocation string) {

@ -1,6 +1,8 @@
package main package main
import ( import (
"JISQueueing/common"
"JISQueueing/db"
"JISQueueing/server" "JISQueueing/server"
"fmt" "fmt"
"github.com/spf13/viper" "github.com/spf13/viper"
@ -19,6 +21,7 @@ func main() {
viper.SetDefault("debug", false) viper.SetDefault("debug", false)
viper.SetDefault("ip", "10.1.3.100") viper.SetDefault("ip", "10.1.3.100")
viper.SetDefault("database", "/etc/queuing/database.sqlite")
viper.SetDefault("server.ssl", true) viper.SetDefault("server.ssl", true)
viper.SetDefault("server.certFile", "/etc/queuing/server.crt") viper.SetDefault("server.certFile", "/etc/queuing/server.crt")
viper.SetDefault("server.keyFile", "/etc/queuing/server.key") 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.username", "IT.Q@jisedu.or.id")
viper.SetDefault("mail.logo", "/etc/queuing/logo.jpg") viper.SetDefault("mail.logo", "/etc/queuing/logo.jpg")
err := viper.ReadInConfig() var config common.Configuration
err := viper.Unmarshal(&config)
if err != nil { if err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok { if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
panic(fmt.Errorf("Fatal error config file: %s \n", err)) panic(fmt.Errorf("Fatal error config file: %s \n", err))
} }
} }
hostLocation := ":" + strconv.Itoa(viper.GetInt("port")) db.Init_DB(config)
mux := server.NewServerMux() hostLocation := ":" + strconv.Itoa(config.Server.Port)
mux := server.NewServerMux(config)
cors := handlers.CORS( cors := handlers.CORS(
handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"}), handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"}),
handlers.AllowedMethods([]string{"POST", "OPTIONS"}), handlers.AllowedMethods([]string{"POST", "OPTIONS"}),
handlers.AllowedOrigins([]string{"*"}), handlers.AllowedOrigins([]string{"*"}),
)(mux) )(mux)
if viper.GetBool("server.ssl") { if config.Server.SSL {
crt := viper.GetString("server.certFile") crt := config.Server.CertFile
key := viper.GetString("server.keyFile") key := config.Server.KeyFile
log.Fatal(http.ListenAndServeTLS(hostLocation, crt, key, cors)) log.Fatal(http.ListenAndServeTLS(hostLocation, crt, key, cors))
} else { } else {
log.Fatal(http.ListenAndServe(hostLocation, cors)) log.Fatal(http.ListenAndServe(hostLocation, cors))
} }
} }

@ -1,6 +1,7 @@
package server package server
import ( import (
"JISQueueing/common"
"JISQueueing/server/socket" "JISQueueing/server/socket"
"net/http" "net/http"
@ -8,7 +9,7 @@ import (
) )
//NewServerMux creates a new http handler object handling API requests //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 := mux.NewRouter()
router.NotFoundHandler = http.HandlerFunc(NotFound) router.NotFoundHandler = http.HandlerFunc(NotFound)
@ -26,7 +27,8 @@ func NewServerMux() http.Handler {
router.PathPrefix("/static").Handler(http.FileServer(http.Dir("./static"))) router.PathPrefix("/static").Handler(http.FileServer(http.Dir("./static")))
router.PathPrefix("/").HandlerFunc(indexHandler) router.PathPrefix("/").HandlerFunc(indexHandler)
socket.StartRedisServer() socket.StartRedisServer(config)
socket.SetConfiguration(config)
return router return router
} }

@ -10,6 +10,11 @@ import (
) )
var queue = make([]common.Ticket, 0) 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) { func newTicket(ticket common.Ticket, who *websocket.Conn) {
queue = append(queue, ticket) 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))) who.WriteMessage(websocket.TextMessage, []byte("success complete "+strconv.Itoa(id)))
notifyTicket(who) notifyTicket(who)
ticket, _ := db.GetTicket(id) //ticket, _ := db.GetTicket(id)
sendDisplayMessage("complete " + strconv.Itoa(table)) sendDisplayMessage("complete " + strconv.Itoa(table))
sendThankYouEmail(ticket)
} }
func cancelTicket(id int, table int, who *websocket.Conn) { func cancelTicket(id int, table int, who *websocket.Conn) {

@ -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()
}

@ -3,7 +3,6 @@ package socket
import ( import (
json "encoding/json" json "encoding/json"
"github.com/go-redis/redis/v7" "github.com/go-redis/redis/v7"
"github.com/spf13/viper"
) )
var client *redis.Client var client *redis.Client
@ -17,7 +16,7 @@ type Message struct {
func StartRedisServer() { func StartRedisServer() {
client = redis.NewClient(&redis.Options{ client = redis.NewClient(&redis.Options{
Addr: viper.GetString("redis.addr"), Addr: config.Redis.Addr,
}) })
_, err := client.Ping().Result() _, err := client.Ping().Result()
@ -34,7 +33,7 @@ func StartRedisServer() {
func sendMessageToRedisChannel(msg Message) { func sendMessageToRedisChannel(msg Message) {
mesg, _ := json.Marshal(msg) 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 { if status.Err() != nil {
println("Error while sending message to redis:", status.Err().Error()) println("Error while sending message to redis:", status.Err().Error())
} }