Last active
February 18, 2017 06:57
-
-
Save dais0n/919359fe3bfd8ac7a668f6e96e664b84 to your computer and use it in GitHub Desktop.
gin and gorm api example
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
// cf. https://medium.com/@etiennerouzeaud/how-to-create-a-basic-restful-api-in-go-c8e032ba3181#.8bappfeoh | |
package main | |
import ( | |
"time" | |
"github.com/gin-gonic/gin" | |
_ "github.com/go-sql-driver/mysql" | |
"github.com/jinzhu/gorm" | |
) | |
type Temperature struct { | |
Id int `gorm:"AUTO_INCREMENT" json:"id"` | |
Temperature float64 `gorm:"not null" json:"temperature"` | |
Humidity float64 `gorm:"not null" json:"humidity"` | |
Created_at time.Time `json:"created_at"` | |
} | |
func InitDb() *gorm.DB { | |
// Openning file | |
db, err := gorm.Open("mysql", "user:password@/database?charset=utf8&parseTime=True&loc=Local") | |
// Display SQL queries | |
db.LogMode(true) | |
// Error | |
if err != nil { | |
panic(err) | |
} | |
return db | |
} | |
func main() { | |
router := gin.Default() | |
router.Use(Cors()) | |
v1 := router.Group("api/v1") | |
{ | |
v1.POST("/temperatures", createTemp) | |
v1.GET("/temperatures", getTemps) | |
} | |
router.Run(":1323") | |
} | |
// HandlerFunc | |
func getTemps(c *gin.Context) { | |
db := InitDb() | |
defer db.Close() | |
var temperatures []Temperature | |
// SELECT * FROM temperatures | |
db.Find(&temperatures) | |
c.JSON(200, temperatures) | |
} | |
func createTemp(c *gin.Context) { | |
db := InitDb() | |
defer db.Close() | |
var temperature Temperature | |
c.Bind(&temperature) | |
db.Create(&temperature) | |
c.JSON(201, gin.H{"success": temperature}) | |
} | |
func Cors() gin.HandlerFunc { | |
return func(c *gin.Context) { | |
c.Writer.Header().Add("Access-Control-Allow-Origin", "*") | |
c.Next() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment