修正params

This commit is contained in:
2023-05-16 05:30:52 +08:00
parent f899e84b48
commit 119f579d70
4 changed files with 59 additions and 18 deletions

View File

@@ -17,6 +17,7 @@ type Dataset struct {
Name string `json:"name"`
Type string `json:"type"`
Info string `json:"info"`
UserID int `json:"user_id"`
CreatedAt time.Time `json:"created_at" gorm:"default:CURRENT_TIMESTAMP;autoCreateTime"`
UpdatedAt time.Time `json:"updated_at" gorm:"default:CURRENT_TIMESTAMP;autoUpdateTime"`
}
@@ -41,14 +42,29 @@ func DatasetsGet(w http.ResponseWriter, r *http.Request) {
}
func DatasetsPost(w http.ResponseWriter, r *http.Request) {
dataset := Dataset{}
if err := configs.ORMDB().Create(&dataset).Error; err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Internal Server Error"))
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Write(utils.ToJSON(dataset))
models.AccountRead(w, r, func(account *models.Account) {
var dataset Dataset
body, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Internal Server Error"))
return
}
defer r.Body.Close()
if err = json.Unmarshal(body, &dataset); err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Internal Server Error"))
return
}
dataset.UserID = account.ID
if err := configs.ORMDB().Create(&dataset).Error; err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Internal Server Error"))
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Write(utils.ToJSON(dataset))
})
}
// 獲取數據集
@@ -96,11 +112,26 @@ func DatasetsItemPatch(w http.ResponseWriter, r *http.Request) {
}
func DatasetsItemDelete(w http.ResponseWriter, r *http.Request) {
dataset := Dataset{ID: utils.ParamInt(mux.Vars(r)["dataset_id"], 0)}
if err := configs.ORMDB().Delete(&dataset).Error; err != nil {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("404 - Not Found"))
return
}
w.WriteHeader(http.StatusNoContent)
models.AccountRead(w, r, func(account *models.Account) {
// 獲取數據集
dataset := Dataset{ID: utils.ParamInt(mux.Vars(r)["id"], 0)}
if err := configs.ORMDB().Find(&dataset).Error; err != nil {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("404 - Not Found"))
return
}
// 只能刪除自己的數據集, 除非是管理員
if dataset.UserID != account.ID && !account.Admin {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte("403 - Forbidden"))
return
}
// 刪除數據集
if err := configs.ORMDB().Delete(&dataset).Error; err != nil {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("404 - Not Found"))
return
}
w.WriteHeader(http.StatusNoContent)
})
}