Skip to content

Instantly share code, notes, and snippets.



Created Jul 3, 2020
What would you like to do?
Trivial REST API returning contents of database
package main
import (
_ ""
. "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 {
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 {
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),
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")
func serve() {
http.HandleFunc("/packages", handleGetPackages)
log.Fatal(http.ListenAndServe(":3001", nil))
func main() {
log.Print("Hello world, this is package service.")
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.