Skip to content

Instantly share code, notes, and snippets.

@clintonhalpin
Last active November 8, 2017 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clintonhalpin/3b480a59c25426925216eeb010742179 to your computer and use it in GitHub Desktop.
Save clintonhalpin/3b480a59c25426925216eeb010742179 to your computer and use it in GitHub Desktop.
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(&quote.Id, &quote.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