-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
57 lines (51 loc) · 1.28 KB
/
main.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
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
sqlFunctions "url-shortener-mysql/sql"
"github.com/gorilla/mux"
)
func main() {
db, err := sqlFunctions.OpenConnection()
if err != nil {
log.Fatal(err.Error())
}
defer db.Close()
dbHandler := newDatabaseHandler(db)
r := mainRouter(db, dbHandler)
http.ListenAndServe(":8000", r)
}
func mainRouter(db *sql.DB, fallback http.HandlerFunc) http.Handler {
router := mux.NewRouter()
router.HandleFunc("/url", func(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
err := sqlFunctions.InsertPath(db, query.Get("path"), query.Get("url"))
if err != nil {
json.NewEncoder(w).Encode("Insertion Failed!")
return
}
json.NewEncoder(w).Encode("Successfully Inserted!")
})
router.PathPrefix("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fallback.ServeHTTP(w, r)
})
return router
}
func newDatabaseHandler(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
pathFromURL, err := sqlFunctions.GetAllPath(db)
if err != nil {
fmt.Println(err.Error())
} else {
path := r.URL.Path
if url, ok := pathFromURL[path]; ok {
http.Redirect(w, r, url, http.StatusFound)
return
}
}
json.NewEncoder(w).Encode("Not Found!")
}
}