Skip to content

Instantly share code, notes, and snippets.

@viggin543
Created July 10, 2020 14:40
Show Gist options
  • Save viggin543/541c2990b26e21ba9681d8fb19bef46f to your computer and use it in GitHub Desktop.
Save viggin543/541c2990b26e21ba9681d8fb19bef46f to your computer and use it in GitHub Desktop.
//# the service
package main
import (
"database/sql"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
"net/http"
)
type Fruit struct {
Id int `json:"id"`
Name string `json:"name"`
}
var con *sql.DB
func init(){
//opening a mysql connection pool with another container
db, err := sql.Open("mysql", "root:password@tcp(host.docker.internal:3306)/payments")
if err != nil {
panic("failed to open a mysql connection")
}
con = db
}
func main() {
r := gin.Default()
r.GET("/fruits", fruits)
r.Run() //server up on 8080
}
// THE REQUEST HANDLER
func fruits(c *gin.Context) {
fruits, err := getFruits()
if err != nil {
c.String(http.StatusInternalServerError, err.Error())
} else {
c.JSON(http.StatusOK, fruits)
}
}
func getFruits() ([]Fruit, error) {
rows, err := con.Query("SELECT * FROM fruits")
if err != nil {
return nil , err
}
fruits := []Fruit{}
for rows.Next() {
var r Fruit
rows.Scan(&r.Id, &r.Name)
fruits = append(fruits, r)
}
return fruits , nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment