Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "net/http"
- "html/template"
- "fmt"
- "database/sql"
- _ "github.com/go-sql-driver/mysql"
- "golang.org/x/crypto/bcrypt"
- )
- var (
- templ *template.Template
- err error
- db *sql.DB
- )
- func init() {
- templ = template.Must(template.ParseGlob("templates/*.html"))
- }
- func main() {
- handleDbConnection()
- http.Handle("/assets/", http.FileServer(http.Dir(".")))
- http.HandleFunc("/", index)
- http.HandleFunc("/login", login)
- http.HandleFunc("/profile", profile)
- fmt.Println("server running")
- http.ListenAndServe(":8080", nil)
- }
- func handleDbConnection() {
- // Create an sql.DB and check for errors
- db, err := sql.Open("mysql", "root:password@/GoStaffManager")
- if err != nil {
- panic(err.Error())
- }
- // sql.DB should be long lived "defer" closes it once this function ends
- defer db.Close()
- // Test the connection to the database
- err = db.Ping()
- if err != nil {
- panic(err.Error())
- } else {
- fmt.Println("working...")
- }
- }
- func index(res http.ResponseWriter, req *http.Request) {
- err = templ.ExecuteTemplate(res, "index.html", nil)
- if err != nil {
- fmt.Sprint("error", err)
- }
- }
- func login(res http.ResponseWriter, req *http.Request) {
- err = templ.ExecuteTemplate(res, "login.html", nil)
- if err != nil {
- fmt.Sprint("error", err)
- }
- // Grab the username/password from the submitted post form
- username := req.FormValue("username")
- password := req.FormValue("password")
- // Grab from the database
- var (
- uname string
- pword string
- )
- // Search the database for the username provided
- // If it exists grab the password for validation
- err := db.QueryRow("SELECT username, password FROM lecturers WHERE username=?", username).Scan(&uname, &pword)
- // If not then redirect to the login page
- if err != nil {
- http.Redirect(res, req, "/login", 301)
- return
- }
- // Validate the password
- err = bcrypt.CompareHashAndPassword([]byte(pword), []byte(password))
- // If wrong password redirect to the login
- if err != nil {
- http.Redirect(res, req, "/login", 301)
- return
- }
- http.Redirect(res, req, "/profile", 301)
- }
- func profile(res http.ResponseWriter, req *http.Request) {
- err = templ.ExecuteTemplate(res, "profile.html", nil)
- if err != nil {
- fmt.Sprint("error", err)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement