golang rest api example

2021-07-10 20:05

阅读:566

标签:tmp   images   building   package   sim   json   get   ret   rop   

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
)

func Database() *gorm.DB {
    //open a db connection
    db, err := gorm.Open("mysql", "root:pass@tcp(127.0.0.1:8889)/gotest?parseTime=true")
    if err != nil {
        panic("failed to connect database")
    }
    return db
}

func main() {

    //Migrate the schema
    db := Database()
    db.AutoMigrate(&Product{})
    router := gin.Default()
    router.GET("/", startPage)
    router.LoadHTMLGlob("templates/*")
    v1 := router.Group("/api/v1/")
    {
        v1.POST("product/", CreateProduct)
        v1.GET("product/", FetchAllProduct)
        v1.GET("product/:id", FetchSingleProduct)
        v1.PUT("product/:id", UpdateProduct)
        v1.DELETE("product/:id", DeleteProduct)
    }
    router.Run()

}

type Product struct {
    gorm.Model
    Name        string `json:"name"`
    Description string `json:"description"`
    Images      string `json:"images"`
    Price       string `json:"price"`
}

type TransformedProduct struct {
    ID          uint   `json:"id"`
    Name        string `json:"name"`
    Description string `json:"description"`
    Images      string `json:"images"`
    Price       string `json:"price"`
}

func CreateProduct(c *gin.Context) {

    product := Product{
        Name:        c.PostForm("name"),
        Description: c.PostForm("description"),
        Images:      c.PostForm("images"),
        Price:       c.PostForm("price"),
    }
    db := Database()
    db.Save(&product)
    c.JSON(http.StatusCreated, gin.H{"status": http.StatusCreated, "message": "Product item created successfully!", "resourceId": product.ID})
}

func FetchAllProduct(c *gin.Context) {
    var products []Product
    var _products []TransformedProduct

    db := Database()
    db.Find(&products)

    if len(products) 

golang rest api example

标签:tmp   images   building   package   sim   json   get   ret   rop   

原文地址:https://www.cnblogs.com/liujitao79/p/9674694.html


评论


亲,登录后才可以留言!