-
Notifications
You must be signed in to change notification settings - Fork 2
/
webserver.go
86 lines (75 loc) · 1.81 KB
/
webserver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"Go-Webserver/webserver/articlehandler"
"bufio"
"database/sql"
"fmt"
"log"
"net/http"
"os"
"time"
_ "github.com/go-sql-driver/mysql"
)
func init() {
if _, noLog := os.Stat("/log.txt"); os.IsNotExist(noLog) {
newLog, err := os.Create("/log.txt")
if err != nil {
log.Fatal(err)
}
newLog.Close()
}
dbString := readConfig("server.confi")
var err error
db, err := sql.Open("mysql", dbString)
check(err)
err = db.Ping()
check(err)
dbChecker := time.NewTicker(time.Minute)
articlehandler.PassDataBase(db)
go checkDB(dbChecker, db)
}
func main() {
http.Handle("/", http.FileServer(http.Dir("./src")))
http.HandleFunc("/articles/", articlehandler.ReturnArticle)
http.HandleFunc("/index.html", articlehandler.ReturnHomePage)
http.HandleFunc("/api/articles", articlehandler.ReturnArticlesForHomePage)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func readConfig(s string) string {
config, err := os.Open(s)
check(err)
defer config.Close()
scanner := bufio.NewScanner(config)
scanner.Scan()
return scanner.Text()
}
func check(err error) {
if err != nil {
errorLog, osError := os.OpenFile("/log.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if osError != nil {
log.Fatal(err)
}
defer errorLog.Close()
textLogger := log.New(errorLog, "go-webserver", log.LstdFlags)
switch err {
case http.ErrMissingFile:
log.Print(err)
textLogger.Fatalln("File missing/cannot be accessed : ", err)
case sql.ErrTxDone:
log.Print(err)
textLogger.Fatalln("SQL connection failure : ", err)
}
log.Println("An error has occured : ", err)
}
}
func checkDB(t *time.Ticker, db *sql.DB) {
for i := range t.C {
err := db.Ping()
if err != nil {
fmt.Println("Db connection failed at : ", i)
check(err)
} else {
fmt.Println("Db connection successful : ", i)
}
}
}