Last active
November 8, 2017 02:58
-
-
Save clintonhalpin/3b480a59c25426925216eeb010742179 to your computer and use it in GitHub Desktop.
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( | |
"log" | |
"net/http" | |
"database/sql" | |
"github.com/gin-gonic/gin" | |
_ "github.com/go-sql-driver/mysql" | |
) | |
var db *sql.DB | |
var err error | |
type Quote struct { | |
Id int `json:"id"` | |
Quote string `json:"quote"` | |
} | |
func (p Quote) getAll() (quotes []Quote, err error) { | |
rows, err := db.Query("SELECT id, quote FROM quotes LIMIT 50") | |
if err != nil { | |
return | |
} | |
for rows.Next() { | |
var quote Quote | |
rows.Scan("e.Id, "e.Quote) | |
quotes = append(quotes, quote) | |
} | |
defer rows.Close() | |
return | |
} | |
func main() { | |
db, err = sql.Open("mysql", "root:@/quote_db") | |
if err != nil { | |
panic(err.Error()) | |
} | |
defer db.Close() | |
err = db.Ping() | |
if err != nil { | |
panic(err.Error()) | |
} | |
router := gin.Default() | |
router.GET("/", func(c *gin.Context) { | |
c.String(200, "find the right words") | |
}) | |
router.GET("/quotes", func(c *gin.Context) { | |
p := Quote{} | |
quotes, err := p.getAll() | |
if err != nil { | |
log.Fatalln(err) | |
} | |
c.JSON(http.StatusOK, gin.H{ | |
"powered_by": "golang", | |
"data": quotes, | |
"total": len(quotes), | |
}) | |
}) | |
router.Run() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment