first commit
This commit is contained in:
100
pkg/api/api.go
Normal file
100
pkg/api/api.go
Normal file
@@ -0,0 +1,100 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-contrib/sessions/cookie"
|
||||
"github.com/gin-gonic/gin"
|
||||
_ "github.com/lib/pq"
|
||||
)
|
||||
|
||||
var db *sql.DB
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
db, err = sql.Open("postgres", os.Getenv("POSTGRES"))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
log.Println("Successfully connected to postgres database")
|
||||
|
||||
// install tables
|
||||
if len(os.Args) >= 2 {
|
||||
if os.Args[1] == "install" {
|
||||
install()
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
// drop tables
|
||||
if os.Args[1] == "drop" {
|
||||
drop()
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
// reinstall
|
||||
if os.Args[1] == "reinstall" {
|
||||
drop()
|
||||
install()
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
// fake data
|
||||
if os.Args[1] == "fake" {
|
||||
fakeData()
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
// unknown Args
|
||||
log.Println("Unknown args", os.Args)
|
||||
os.Exit(2)
|
||||
}
|
||||
}
|
||||
|
||||
func NewAPI() *gin.Engine {
|
||||
router := gin.Default()
|
||||
|
||||
// session
|
||||
store := cookie.NewStore([]byte("Miku saves the world!"))
|
||||
router.Use(sessions.Sessions("ais", store))
|
||||
|
||||
// entry point html
|
||||
router.GET("/", func(c *gin.Context) {
|
||||
c.File("./web/public/index.html")
|
||||
})
|
||||
|
||||
group := router.Group("/api")
|
||||
|
||||
// json error middleware
|
||||
group.Use(func(c *gin.Context) {
|
||||
c.Next()
|
||||
if len(c.Errors) > 0 {
|
||||
c.JSON(-1, gin.H{
|
||||
"errors": c.Errors.Errors(),
|
||||
"note": "gin api error handler",
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
group.POST("/login", handelLogin)
|
||||
group.GET("/login", handelGetLoginSession)
|
||||
group.POST("/register", handelRegister)
|
||||
group.POST("/logout", handelLogout)
|
||||
|
||||
customer := group.Group("/customer")
|
||||
customer.GET("/market", handleGetMarket)
|
||||
customer.GET("/market/distance", handleGetMarketByDistance)
|
||||
customer.GET("/market/:marketid", handleGetGoods)
|
||||
customer.POST("/market/:marketid/:goodsid", handleBuy)
|
||||
customer.GET("/purchase", handleGetPurchaseHistory)
|
||||
customer.DELETE("/purchase/:purchaseid", handleDeletePurchaseHistory)
|
||||
customer.GET("/purchase/report", handleCustomerReport)
|
||||
|
||||
supplier := group.Group("/supplier")
|
||||
supplier.GET("/goods", handleGetGodsBySupplier)
|
||||
supplier.POST("/goods", handleCreateGoods)
|
||||
|
||||
return router
|
||||
}
|
||||
Reference in New Issue
Block a user