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"`
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
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) {

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

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

@ -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) {

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