Skip to content

Instantly share code, notes, and snippets.

@tomekc

tomekc/database.go

Created Jul 3, 2020
Embed
What would you like to do?
Trivial REST API returning contents of database
package main
import (
"context"
"database/sql"
"encoding/json"
_ "github.com/go-sql-driver/mysql"
"net/http"
. "strings"
)
import "log"
var (
ctx context.Context
db *sql.DB
)
func dbConn() (db *sql.DB) {
dbDriver := "mysql"
dbUser := "root"
dbPass := "root"
dbName := "hotel"
db, err := sql.Open(dbDriver, dbUser+":"+dbPass+"@/"+dbName)
if err != nil {
panic(err.Error())
}
return db
}
type Package struct {
Id int
Name string
Amount float32
Currency string
}
func get_data() []Package {
db := dbConn()
rows, err := db.Query("select id,package_name,package_curr,amount from packages_v2 limit 10;")
if err != nil {
panic(err.Error())
}
var Packages = []Package{}
for rows.Next() {
var id int
var name, curr string
var amount float32
err = rows.Scan(&id, &name, &curr, &amount)
var pkg = Package{
Id: id,
Name: name,
Amount: amount,
Currency: ToUpper(curr),
}
log.Print(pkg)
Packages = append(Packages, pkg)
}
return Packages
}
func handleGetPackages(writer http.ResponseWriter, r *http.Request) {
var data = get_data()
writer.Header().Add("Content-Type", "application/json")
json.NewEncoder(writer).Encode(data)
}
func serve() {
http.HandleFunc("/packages", handleGetPackages)
log.Fatal(http.ListenAndServe(":3001", nil))
}
func main() {
log.Print("Hello world, this is package service.")
get_data()
serve()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.