In this tutorial we’ll learn how to use Golang and MySQL together to build a login/signup system.
Before starting make sure you have MySQL installed and running.
GET THE REQUIRED PACKAGES
The driver to connect MySQL and Go
go get github.com/go-sql-driver/mysql
Bcrypt to encrypt passwords before saving them
go get golang.org/x/crypto/bcrypt
CREATE A SERVER
package main
import “net/http”
func homePage(res http.ResponseWriter, req *http.Request) {
http.ServeFile(res, req, “index.html”)
}
func main() {
http.HandleFunc(“/”, homePage)
http.ListenAndServe(“:8080”, nil)
}
Create index.html to link to a login/signup page
Home Page
Home Page
Login
Sign Up
CONNECT TO MYSQL
First import the MySQL driver
import “database/sql”
import _ “github.com/go-sql-driver/mysql”
Notice the _ before the driver. Instead of relying on the driver we use “database/sql” in case we want to change the driver in the future.
Now create a global sql.DB object and open a connection to MySQL
package main
import “database/sql”
import _ “github.com/go-sql-driver/mysql”
import “net/http”
// Global sql.DB to access the database by all handlers
var db *sql.DB
var err error
func homePage(res http.ResponseWriter, req *http.Request) {
http.ServeFile(res,
Original URL: http://feedproxy.google.com/~r/feedsapi/BwPx/~3/bWUaVMl2ALc/
Like this:
Like Loading...
Original article