我的 Go 编程新手遇到问题,例如:无效的内存地址或 nil 指针取消引用
有时我可以解决问题,但这让我感到困惑。这是处理程序级别的代码,我尝试实现 ###p.repo.UpdateProfile() 和来自 r.body 解码的数据
//UpdateProfile handler
func (p *Profile) UpdateProfile(w http.ResponseWriter, r *http.Request) {
var (
errForm models.ErrorForm
resp models.Response
respError models.ErrorResponse
errField models.ErrField
data *models.EditProfile
)
userid := r.Context().Value(viper.GetString("token.userid"))
errDecode := json.NewDecoder(r.Body).Decode(&data)
errPayload := p.repo.UpdateProfile(r.Context(), data, userid)
if errPayload.Error() == "username_exist" {
respError.Message = "username already taken"
respError.Status = 422
lib.ResJSON(w, respError.Status, respError)
return
}
lib.Catch(errPayload)
resp.Data = ""
resp.Message = "Success"
resp.Status = 200
lib.ResJSON(w, resp.Status, resp)
}
和方法如下:
func (m *mysqlProfileRepo) UpdateProfile(ctx context.Context, p *models.EditProfile, userid interface{}) error {
query := ""
var checkexist int
row1, err1 := m.Conn.QueryContext(ctx, query, p.Username)
if err1 != nil {
return err1
}
for row1.Next() {
if errSc1 := row1.Scan(&checkexist); errSc1 != nil {
return errors.New("error_scan_db")
}
}
if checkexist != 0 {
return errors.New("username_exist")
}
query1 := ""
query2 := ""
stmts := []*lib.PipelineStmt{
lib.NewPipelineStmt(query1, p.Image, p.Location, p.Link, p.Bio, p.Birthday, userid),
lib.NewPipelineStmt(query2, p.Username, p.Fullname, userid),
}
errTrx := lib.WithTransaction(m.Conn, func(tx lib.Transaction) error {
_, errRunPipe := lib.RunPipeline(tx, stmts...)
return errRunPipe
})
if errTrx != nil {
return errTrx
}
return nil
}
慕森卡
相关分类