このストラクトにjsonで返ってきた値をしたのストラクトに当てはめ、値を更新したい.
ちょっとでもわかる人いたらお願いします。本当至急です。
本当にわからないのでお願いします。
※実際のコードとは少し異なります。
一番上のストラクトにデータがゲットから取得され、それを、二番目のリクエストボディーに移したいのですがやり方がわかりません。
そのリクエストボディーを使ってアップデートファンクション(一番下)を行いたいのですが、技術が足りず、前に進めなくなってしまいました。
コメントも入っているので、そちらも読んでいただけたらと思います。
post
1type PostView struct { 2 Id int64 `json:"id"` 3 UserId int64 `json:"userid"` 4 GroupId int64 `json:"groupid"` 5 Title string `json:"title"` 6 Content string `json:"content"` 7 Comment string `json:"comment"` 8 PostFile sql.NullString `json:"postfile"` 9 Time int `json:"time"` 10 CreatedAt *time.Time `json:"createdAt"` 11 UpdatedAt *time.Time `json:"updatedAt"` 12}
request
1type PostRequestBody struct { 2 Title string 3 Content string 4 Comment string 5 PostFile string 6 Time int 7}
binding
1func (p *PostRequestBody) FieldMap(req *http.Request) binding.FieldMap { 2 return binding.FieldMap{ 3 &p.Title: "title", 4 &p.Content: "content", 5 &p.Comment: "comment", 6 &p.PostFile: "postfile", 7 &p.Time: "time", 8 } 9}
get
1func GetPost(postId int64) PostView { 2 query := PostQuery + ` 3 WHERE p.id = ? 4 ` 5 6 var post PostView 7 err := DbMap.SelectOne(&post, query, postId) 8 helpers.CheckErr(err, "Executing query failed") 9 10 return post 11}
update
1func UpdatePost(post Post) Post { 2 trans, err := DbMap.Begin() 3 helpers.CheckErr(err, "Start new transaction failed") 4 5 now := time.Now() 6 post.UpdatedAt = &now 7 8 _, err = trans.Update(&post) 9 CheckTransErr(trans, err, "Update post failed") 10 11 err = trans.Commit() 12 CheckTransErr(trans, err, "Commit transaction failed") 13 14 return post 15}
update
1func UpdatePost(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { 2 userId, err := strconv.ParseInt(ps.ByName("userId"), 10, 0) 3 helpers.CheckErr(err, "Invalid userId") 4 postId, err := strconv.ParseInt(ps.ByName("postId"), 10, 0) 5 helpers.CheckErr(err, "Invalid postId") 6 7 8 user := models.GetUser(userId) 9 log.Println(user) 10 11 switch user.GroupId { 12 case 1: 13 14 p := models.GetPost(postId) 15//取得したpostが入ってきている。 16//でも、getpostはstructが違うためbiningできない 17//それをどうにかして、bindし、変更を加えたい。 18 19//p := new(models.PostRequestBody)//新しいのを作ることができる 20 errs := binding.Bind(req, p) 21 if errs.Len() > 0 { 22 log.Println(errs) 23 R.JSON(w, 422, errs) 24 return 25 } 26 27 post := models.Post{ 28 Title: p.Title, 29 Content: p.Content, 30 Comment: p.Comment, 31 PostFile: sql.NullString{ 32 Valid: len(p.PostFile) > 0, 33 String: p.PostFile, 34}, 35 Time: p.Time, 36 } 37 R.JSON(w, http.StatusOK, models.UpdatePost(post)) 38 default: 39 R.JSON(w, http.StatusBadRequest, map[string]interface{}{ 40 "code": http.StatusBadRequest, 41 "message": http.StatusText(http.StatusBadRequest), 42 }) 43 44 } 45}
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/06/23 11:07