Created
July 3, 2020 05:55
-
-
Save tomekc/3a9a0a7ab51750526ac71b566c6f627e to your computer and use it in GitHub Desktop.
Trivial REST API returning contents of database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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