コード例 #1
0
ファイル: route_edit_event.go プロジェクト: cwc/asset-tracker
func editEvent(env mango.Env) (mango.Status, mango.Headers, mango.Body) {
	db := env["AssetTracker.db"].(*sql.DB)
	req := env.Request()

	switch req.Method {
	case "GET":
		break
	case "POST":
		event := models.Event{}

		req.ParseForm()

		decoder := schema.NewDecoder()
		err := decoder.Decode(&event, req.Form)
		if err != nil {
			log.Println(err)
		}

		log.Printf("Received Event %#v", event)

		_, err = crud.Insert(db, "events", "event_id", event)
		if err != nil {
			log.Println(err)
			return internalServerError()
		}

		return 201, mango.Headers{}, mango.Body("Event saved")
	}

	return 404, mango.Headers{}, mango.Body("404")
}
コード例 #2
0
ファイル: route_edit_asset.go プロジェクト: cwc/asset-tracker
func editAsset(env mango.Env) (mango.Status, mango.Headers, mango.Body) {
	db := env["AssetTracker.db"].(*sql.DB)
	tmpl := env["AssetTracker.tpl"].(*template.Template)
	req := env.Request()

	switch req.Method {
	case "GET":
		var asset models.Asset
		uriParams := env["Routing.matches"].([]string)

		if len(uriParams) > 1 {
			id, err := strconv.ParseInt(uriParams[1], 10, 64)
			if err != nil {
				log.Println(err)
				return defaultHandler(env)
			}

			asset, err = models.GetAssetById(db, id)
			if err != nil {
				log.Println(err)
				return internalServerError()
			}
		} else {
			asset = models.Asset{}
		}

		args := map[string]interface{}{
			"Title": "Edit Asset",
			"Asset": asset,
		}

		var buf bytes.Buffer
		if err := tmpl.ExecuteTemplate(&buf, "editAsset.tpl", args); err != nil {
			log.Println(err)
			return internalServerError()
		}

		return 200, mango.Headers{}, mango.Body(buf.String())
	case "POST":
		asset := models.Asset{}

		req.ParseForm()

		decoder := schema.NewDecoder()
		err := decoder.Decode(&asset, req.Form)
		if err != nil {
			log.Println(err)
		}

		log.Printf("Received Asset %#v", asset)

		// Update or create the new asset
		if asset.Id > 0 {
			err = crud.Update(db, "assets", "asset_id", asset)
		} else {
			_, err = crud.Insert(db, "assets", "asset_id", asset)
		}

		if err != nil {
			log.Println(err)
			return internalServerError()
		}

		return 201, mango.Headers{}, mango.Body("Asset saved")
	}

	return 404, mango.Headers{}, mango.Body("404")
}