-
-
Notifications
You must be signed in to change notification settings - Fork 415
Closed
Description
I am learning Go-Lang and tried to create a DB using the initDB() method, but I am unable to make connection. I am getting this error: "dial tcp 127.0.0.1:3306: connect: connection refused
panic: failed to connect database. " . Can Anyone help me what corrections are required.
package` main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
// Site is ...
type Site struct {
// gorm.Model
Pos uint `json:"pos" gorm:"primary_key"`
Name string `json:"name"`
Image string `json:"image"`
}
var db *gorm.DB
func initDB() {
var err error
dataSourceName := "root:@tcp(localhost:3306)/?parseTime=True"
db, err = gorm.Open("mysql", dataSourceName)
if err != nil {
fmt.Println(err)
panic("failed to connect database")
}
// Create the database. This is a one-time step.
// Comment out if running multiple times - You may see an error otherwise
db.Exec("CREATE DATABASE sites_db")
db.Exec("USE sites_db")
// Migration to create tables for Order and Item schema
db.AutoMigrate(&Site{})
}
func createSite(w http.ResponseWriter, r *http.Request) {
var site Site
json.NewDecoder(r.Body).Decode(&site)
// Creates new order by inserting records in the `orders` and `items` table
db.Create(&site)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(site)
}
func getSites(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var sites []Site
db.Preload("Items").Find(&sites)
json.NewEncoder(w).Encode(sites)
}
func main() {
router := mux.NewRouter()
// Create
router.HandleFunc("/site", createSite).Methods("POST")
// Read
//router.HandleFunc("/site/{pos}", getSite).Methods("GET")
// Read-all
router.HandleFunc("/site", getSites).Methods("GET")
// Update
//router.HandleFunc("/site/{pos}", updateSite).Methods("PUT")
// Delete
//router.HandleFunc("/site/{pos}", deleteSite).Methods("DELETE")
// Initialize db connection
initDB()
log.Fatal(http.ListenAndServe(":8080", router))
}
```````````````````````````````````````````````
Metadata
Metadata
Assignees
Labels
No labels