Skip to content
Snippets Groups Projects
api.go 1.28 KiB
Newer Older
  • Learn to ignore specific revisions
  • package api
    
    import (
    	"github.com/gorilla/mux"
    	"gorm.io/driver/sqlite"
    	"gorm.io/gorm"
    )
    
    type api struct {
    
    	db      *gorm.DB
    	signKey []byte
    
    }
    
    func initDB(dbPath string) (*gorm.DB, error) {
    	db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
    	if err != nil {
    		return nil, err
    	}
    
    	db.AutoMigrate(&Member{})
    
    meskio's avatar
    meskio committed
    	db.AutoMigrate(&Product{})
    
    func Init(dbPath string, signKey string, r *mux.Router) error {
    
    	db, err := initDB(dbPath)
    	if err != nil {
    		return err
    	}
    
    
    	a := api{db, []byte(signKey)}
    	r.HandleFunc("/signin", a.SignIn).Methods("POST")
    
    meskio's avatar
    meskio committed
    
    
    	r.HandleFunc("/member", a.auth(a.ListMembers)).Methods("GET")
    	r.HandleFunc("/member", a.auth(a.AddMember)).Methods("POST")
    	r.HandleFunc("/member/{num:[0-9]+}", a.auth(a.GetMember)).Methods("GET")
    	r.HandleFunc("/member/{num:[0-9]+}", a.auth(a.UpdateMember)).Methods("PUT")
    	r.HandleFunc("/member/{num:[0-9]+}", a.auth(a.DeleteMember)).Methods("DELETE")
    
    meskio's avatar
    meskio committed
    
    	r.HandleFunc("/product", a.auth(a.ListProducts)).Methods("GET")
    	r.HandleFunc("/product", a.auth(a.AddProduct)).Methods("POST")
    	r.HandleFunc("/product/{code:[0-9]+}", a.auth(a.GetProduct)).Methods("GET")
    	r.HandleFunc("/product/{code:[0-9]+}", a.auth(a.UpdateProduct)).Methods("PUT")
    	r.HandleFunc("/product/{code:[0-9]+}", a.auth(a.DeleteProduct)).Methods("DELETE")