Created
July 4, 2020 20:47
-
-
Save viggin543/0e8488e5227bded0e1d66ec7955e2520 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| # the service | |
| package main | |
| import ( | |
| "database/sql" | |
| "fmt" | |
| "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 := getFruits() | |
| c.JSON(http.StatusOK, fruits) | |
| } | |
| func getFruits() []Fruit { | |
| rows, _ := con.Query("SELECT * FROM fruits") | |
| fruits := []Fruit{} | |
| for rows.Next() { | |
| var r Fruit | |
| rows.Scan(&r.Id, &r.Name) | |
| fruits = append(fruits, r) | |
| } | |
| return fruits | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment