How to use Error method of json Package

Best Go-testdeep code snippet using json.Error

main.go

Source:main.go Github

copy

Full Screen

...106 return107 }108 var idReq ClubIDRequest109 if err := ctx.ShouldBindJSON(&idReq);err != nil {110 log.Error(err)111 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))112 return113 }114 err = db.UpdateClubPublishedOrNot(idReq.ClubId, false)115 if err != nil {116 log.Error(err)117 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))118 return119 }120 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(nil))121}122func getOneClubInfo(ctx *gin.Context) {123 //check admin or not124 account, err := getAdminUser(ctx)125 if err != nil {126 return127 }128 if !account.IsAdmin {129 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.NO_PERMISSION, nil))130 return131 }132 //check club id133 clubId := ctx.Query("club_id")134 if clubId == "" {135 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))136 return137 }138 //get response club info139 clubInfo, err := db.GetClubInfoCountByClubId(clubId)140 if gorm.IsRecordNotFoundError(err) {141 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))142 return143 }144 if err != nil {145 log.Error(err)146 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))147 return148 }149 tagIds, pictureIds, err := getClubTagIdsAndPictureIds(clubInfo.ClubID,150 clubInfo.Pic1ID, clubInfo.Pic2ID, clubInfo.Pic3ID, clubInfo.Pic4ID, clubInfo.Pic5ID, clubInfo.Pic6ID)151 if err != nil {152 log.Error(err)153 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))154 return155 }156 club := constructClubInfoCountPost(clubInfo, tagIds, pictureIds)157 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(club))158}159type UpdateUserPost struct {160 NewLoopUID string `json:"new_loop_uid"`161 LoopUserName string `json:"loop_user_name"`162 SrcLoopUID string `json:"src_loop_uid"`163}164func updateRegisterUser(ctx *gin.Context) {165 //check request param166 var updateUserPost UpdateUserPost167 if err := ctx.ShouldBindJSON(&updateUserPost); err != nil {168 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))169 log.Error(err)170 return171 }172 if len(updateUserPost.NewLoopUID) != 64 ||173 len(updateUserPost.LoopUserName) == 0 {174 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))175 return176 }177 if !strings.HasSuffix(updateUserPost.SrcLoopUID, "00000000000000000000000000000000") {178 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, "Check source uid format"))179 return180 }181 //update registered user, whether source user exists or not182 var user db.UpdateUser183 user.SrcLoopUID = updateUserPost.SrcLoopUID184 user.LoopUID = updateUserPost.NewLoopUID185 user.LoopUserName = updateUserPost.LoopUserName186 err := user.Update()187 if err != nil {188 log.Error(err)189 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))190 return191 }192 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(nil))193}194type AccountPost struct {195 AccountId string `json:"account_id"`196 Email string `json:"email"`197 PhoneNum string `json:"phone_num"`198 Note string `json:"note"`199}200func updateAccountInfo(ctx *gin.Context) {201 //check admin or not202 account, err := getAdminUser(ctx)203 if err != nil {204 return205 }206 if !account.IsAdmin {207 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.NO_PERMISSION, nil))208 return209 }210 var accountReq AccountPost211 if err := ctx.ShouldBindJSON(&accountReq);err!=nil {212 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))213 log.Error(err)214 return215 }216 if account.AccountID == "" {217 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))218 return219 }220 _, err = db.GetAccountByUserId(accountReq.AccountId)221 if gorm.IsRecordNotFoundError(err) {222 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))223 return224 }225 if err != nil {226 log.Error(err)227 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))228 return229 }230 adminAccount := db.AdminAccount{231 AccountID: accountReq.AccountId,232 Email: accountReq.Email,233 PhoneNum: accountReq.PhoneNum,234 Note: accountReq.Note,235 }236 err = adminAccount.Update()237 if err != nil {238 log.Error(err)239 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))240 return241 }242 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(nil))243}244func logout(ctx *gin.Context) {245 // if user exist in the session246 session := sessions.Default(ctx)247 result := session.Get(USER)248 if result == nil {249 ctx.JSON(http.StatusUnauthorized, httpserver.ConstructResponse(httpserver.NOT_AUTHORIZED, false))250 return251 }252 // delete the user in the session253 session.Delete(USER)254 if err := session.Save(); err != nil {255 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))256 return257 }258 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(nil))259}260func getUnreadViewList(ctx *gin.Context) {261 //check user262 user, err := getAppUser(ctx)263 if err != nil {264 log.Error(err)265 return266 }267 //get user view list, create new view list when not found.268 viewList, err := db.GetLatestViewListByUID(user.LoopUID)269 if gorm.IsRecordNotFoundError(err) {270 //try to create view list271 viewList = &db.ViewList{272 LoopUID: user.LoopUID,273 ViewListID: uuid.New().String(),274 }275 err = viewList.Insert()276 //fail to create view list277 if err != nil {278 log.Error("fail to create view list when register, error:", err)279 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))280 return281 }282 }283 if err != nil {284 log.Error(err)285 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))286 return287 }288 //Get not read club infos attached with current user favourite or not289 notReadClubInfos, err := db.GetUnreadPublishedFavouriteClubInfo(user.LoopUID, viewList.ViewListID)290 if err != nil {291 log.Error(err)292 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))293 return294 }295 //construct response club info from DB query result296 responseClubs, err := getResponseFromFavouriteClubInfos(notReadClubInfos)297 if err != nil {298 log.Error(err)299 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))300 return301 }302 //shuffle response club infos303 rand.Seed(time.Now().UnixNano())304 rand.Shuffle(len(responseClubs), func(i, j int) { responseClubs[i], responseClubs[j] = responseClubs[j], responseClubs[i] })305 //construct response unread view list306 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(responseClubs))307}308type ClubIDRequest struct {309 ClubId string `json:"club_id"`310}311//Marks club already read by user in current view list.312func markClubReadInViewList(ctx *gin.Context) {313 //check user314 user, err := getAppUser(ctx)315 if err != nil {316 log.Error(err)317 return318 }319 //get request params320 var idReq ClubIDRequest321 if err := ctx.ShouldBindJSON(&idReq); err != nil {322 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))323 log.Error(err)324 return325 }326 //check user and view list327 viewList, err := db.GetLatestViewListByUID(user.LoopUID)328 if err != nil {329 log.Error(err)330 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))331 return332 }333 //check club334 _, err = db.GetClubInfoByClubId(idReq.ClubId)335 if gorm.IsRecordNotFoundError(err) {336 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))337 return338 }339 if err != nil {340 log.Error(err)341 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))342 return343 }344 //save read info into DB345 viewLog := db.ViewListLog{346 ViewListID: viewList.ViewListID,347 LoopUID: user.LoopUID,348 ClubID: idReq.ClubId,349 }350 err = viewLog.Insert()351 if err != nil {352 log.Error(err)353 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))354 return355 }356 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(nil))357}358//Returns a new club view list and corresponding id.359// Club view list is current all published clubs that sequence shuffled.360func createNewViewList(ctx *gin.Context) {361 //check user362 user, err := getAppUser(ctx)363 if err != nil {364 log.Error(err)365 return366 }367 //create new view list info into368 viewList := db.ViewList{369 LoopUID: user.LoopUID,370 ViewListID: uuid.New().String(),371 }372 err = viewList.Insert()373 if err != nil {374 log.Error(err)375 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))376 return377 }378 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(nil))379}380func getClubInfoOfGivenTags(ctx *gin.Context) {381 //check user382 user, err := getAppUser(ctx)383 if err != nil {384 log.Error(err)385 return386 }387 //get request tags388 tagStr := ctx.Query("tag_id")389 if tagStr == "" {390 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, "tags not specified"))391 return392 }393 tagIDs := strings.Split(tagStr, ";")394 //validate tags395 tags, err := db.GetClubTagsByTagIds(tagIDs)396 if err != nil {397 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))398 return399 }400 if len(tags) != len(tagIDs) {401 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, "invalid tag id"))402 return403 }404 //get clubs having given tag id.405 relationships, err := db.GetTagRelationshipsByTagIDs(tagIDs)406 if err != nil {407 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))408 return409 }410 //unite club ids from clubs411 clubIDs := make([]string, 0)412 for _, relation := range relationships {413 clubIDs = append(clubIDs, relation.ClubID)414 }415 favouriteClubInfos, err := db.GetAllPublishedFavouriteClubInfoByClubIDs(user.LoopUID, clubIDs)416 if err != nil {417 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))418 return419 }420 responseClubs, err := getResponseFromFavouriteClubInfos(favouriteClubInfos)421 if err != nil {422 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))423 }424 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(responseClubs))425}426//FavouriteClubInfo is a assist struct to response club info to app user.427type FavouriteClubInfo struct {428 ClubInfoPost429 //is user favourite to this club430 Favourite bool `json:"favourite"`431}432func GetAllClubs(ctx *gin.Context) {433 //check user434 user, err := getAppUser(ctx)435 if err != nil {436 log.Error(err)437 return438 }439 favouriteClubInfos, err := db.GetAllPublishedFavouriteClubInfo(user.LoopUID)440 if err != nil {441 log.Error(err)442 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))443 return444 }445 responseInfo, err := getResponseFromFavouriteClubInfos(favouriteClubInfos)446 if err != nil {447 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))448 }449 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(responseInfo))450}451//Constructs club response info from DB query result452func getResponseFromFavouriteClubInfos(favouriteClubInfos []db.FavouriteClubInfo) ([]FavouriteClubInfo, error) {453 clubInfos := make([]FavouriteClubInfo, 0)454 for _, clubInfo := range favouriteClubInfos {455 tagIDs, pictureIDs, err := getClubTagIdsAndPictureIds(clubInfo.ClubID,456 clubInfo.Pic1ID, clubInfo.Pic2ID, clubInfo.Pic3ID, clubInfo.Pic4ID, clubInfo.Pic5ID, clubInfo.Pic6ID)457 if err != nil {458 return clubInfos, err459 }460 infoPost := ClubInfoPost{461 ClubID: clubInfo.ClubID,462 Name: clubInfo.Name,463 Website: clubInfo.Website,464 Email: clubInfo.Email,465 GroupLink: clubInfo.GroupLink,466 VideoLink: clubInfo.VideoLink,467 Published: clubInfo.Published,468 Description: clubInfo.Description,469 LogoId: clubInfo.LogoID,470 TagIds: tagIDs,471 PictureIds: pictureIDs,472 }473 responseInfo := FavouriteClubInfo{474 ClubInfoPost: infoPost,475 Favourite: clubInfo.Favourite,476 }477 clubInfos = append(clubInfos, responseInfo)478 }479 return clubInfos, nil480}481//Sets club is unfavourite to user482func setUnfavouriteClub(ctx *gin.Context) {483 doFavouriteClub(ctx, false)484}485//Sets club is favourite to user486func setFavouriteClub(ctx *gin.Context) {487 doFavouriteClub(ctx, true)488}489//Sets club is whatever favourite or unfavourite to user490func doFavouriteClub(ctx *gin.Context, favourite bool) {491 //check user492 user, err := getAppUser(ctx)493 if err != nil {494 log.Error(err)495 return496 }497 //check club id498 clubID := ctx.Param("clubID")499 _, err = db.GetClubInfoByClubId(clubID)500 if gorm.IsRecordNotFoundError(err) {501 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))502 return503 }504 if err != nil {505 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))506 log.Error(err)507 return508 }509 err = setFavouriteStateAndLogIntoDB(user.LoopUID, clubID, favourite)510 if err != nil {511 log.Error(err)512 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))513 return514 }515 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(nil))516}517func setFavouriteStateAndLogIntoDB(loopUID, clubID string, like bool) error {518 //insert favourite club, rolls back when error occurs519 favourite := db.UserFavourite{520 LoopUID: loopUID,521 ClubID: clubID,522 Favourite: like,523 }524 txDb := db.DB.Begin()525 err := favourite.InsertOrUpdate(txDb)526 if err != nil {527 txDb.Rollback()528 return err529 }530 //what action user is doing531 var action string532 if like {533 action = db.FAVORITE_ACTION534 } else {535 action = db.UNFAVORITE_ACTION536 }537 //insert log, rolls back when error occurs538 l := db.UserFavouriteLog{539 LoopUID: loopUID,540 ClubID: clubID,541 Action: action,542 }543 err = l.Insert(txDb)544 if err != nil {545 txDb.Rollback()546 return err547 }548 txDb.Commit()549 return nil550}551//Returns the clubs that user favourite, whether published or not.552func getFavouriteClubList(ctx *gin.Context) {553 user, err := getAppUser(ctx)554 if err != nil {555 log.Error(err)556 return557 }558 //get favorite club ids559 favourites, err := db.GetUserFavouritesByUID(user.LoopUID)560 clubIds := make([]string, 0)561 for _, favourite := range favourites {562 clubIds = append(clubIds, favourite.ClubID)563 }564 //get club infos565 clubInfos, err := db.GetPublishedClubInfosByClubIds(clubIds)566 //construct response info567 clubInfoResponses := make([]ClubInfoPost, 0)568 for _, clubInfo := range clubInfos {569 tagIDs, pictureIDs, err := getClubTagIdsAndPictureIds(clubInfo.ClubID,570 clubInfo.Pic1ID, clubInfo.Pic2ID, clubInfo.Pic3ID, clubInfo.Pic4ID, clubInfo.Pic5ID, clubInfo.Pic6ID)571 if err != nil {572 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))573 return574 }575 clubInfoResponse := constructClubInfoPost(&clubInfo, tagIDs, pictureIDs)576 clubInfoResponses = append(clubInfoResponses, *clubInfoResponse)577 }578 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(clubInfoResponses))579}580func getAppUserInfo(ctx *gin.Context) {581 user, err := getAppUser(ctx)582 if err != nil {583 log.Error(err)584 return585 }586 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(user))587}588//Get user from DB by uid set in request header.589func getAppUser(ctx *gin.Context) (*db.UserList, error) {590 userId := ctx.GetHeader("user-id")591 if userId == "" {592 ctx.JSON(http.StatusUnauthorized, httpserver.ConstructResponse(httpserver.NOT_AUTHORIZED, nil))593 return nil, errors.New("header not found")594 }595 user, err := db.GetAppUserByUid(userId)596 if gorm.IsRecordNotFoundError(err) {597 ctx.JSON(http.StatusUnauthorized, httpserver.ConstructResponse(httpserver.NOT_AUTHORIZED, nil))598 return nil, errors.New("user not found")599 }600 if err != nil {601 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))602 return nil, err603 }604 return user, nil605}606type UserPost struct {607 LoopUID string `json:"loop_uid"`608 LoopUserName string `json:"loop_user_name"`609}610//Used to register for LOOP user.611func registerAppUser(ctx *gin.Context) {612 userPost := new(UserPost)613 if err := ctx.ShouldBindJSON(userPost); err != nil {614 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))615 log.Error(err)616 return617 }618 if len(userPost.LoopUID) != 64 || len(userPost.LoopUserName) == 0 {619 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))620 return621 }622 foundUser, err := db.GetAppUserByUid(userPost.LoopUID)623 if err != nil && !gorm.IsRecordNotFoundError(err) {624 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))625 log.Print(err)626 return627 }628 if foundUser.LoopUID != "" {629 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.USER_ALREADY_REGISTERED, nil))630 return631 }632 //register new use633 user := db.UserList{634 LoopUID: userPost.LoopUID,635 LoopUserName: userPost.LoopUserName,636 JoinTime: time.Now(),637 }638 err = user.Insert()639 if err != nil {640 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))641 log.Error(err)642 return643 }644 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(nil))645}646func ifAuthorized(ctx *gin.Context) {647 _, err := getAdminUser(ctx)648 if err != nil {649 return650 }651 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(true))652}653//Returns current login user654func getCurrUser(ctx *gin.Context) {655 account, err := getAdminUser(ctx)656 if err != nil {657 return658 }659 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(account))660}661func appGetAllTags(ctx *gin.Context) {662 _, err := getAppUser(ctx)663 if err != nil {664 return665 }666 tags, err := db.GetAllClubTags()667 if err != nil {668 log.Error(err)669 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))670 return671 }672 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(tags))673}674func adminGetAllTags(ctx *gin.Context) {675 _, err := getAdminUser(ctx)676 if err != nil {677 return678 }679 tags, err := db.GetAllClubTags()680 if err != nil {681 log.Error(err)682 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))683 return684 }685 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(tags))686}687func serveStaticPicture(ctx *gin.Context) {688 pictureID := ctx.Param("pictureID")689 if pictureID == "" {690 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PICTURE_ID, nil))691 return692 }693 fileName, err := db.GetPictureNameById(pictureID)694 if gorm.IsRecordNotFoundError(err) {695 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PICTURE_ID, nil))696 return697 }698 if err != nil {699 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))700 return701 }702 basePath := path.Join(globalConfig.General.PictureStoragePath, fileName)703 img, err := os.Open(basePath)704 if err != nil {705 if strings.HasSuffix(err.Error(), "The system cannot find the file specified.") {706 log.Error(err)707 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.NOT_FOUND, nil))708 return709 }710 log.Error(err)711 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))712 return713 }714 defer img.Close()715 ctx.Writer.Header().Set("Content-Type", "image/jpeg")716 _, err = io.Copy(ctx.Writer, img)717 if err != nil {718 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))719 return720 }721}722// Get User information from request context.723func getAdminUser(ctx *gin.Context) (*db.AdminAccount, error) {724 session := sessions.Default(ctx)725 result := session.Get(USER)726 if result == nil {727 ctx.JSON(http.StatusUnauthorized, httpserver.ConstructResponse(httpserver.NOT_AUTHORIZED, false))728 return nil, errors.New("user invalid")729 }730 user := result.(db.AdminAccount)731 return &user, nil732}733// Returns the club info of current login user.734func getSelfClubInfo(ctx *gin.Context) {735 account, err := getAdminUser(ctx)736 if err != nil {737 return738 }739 if account.IsAdmin {740 emptyClubInfo := ClubInfoPost{741 TagIds: make([]string, 0),742 PictureIds: make([]string, 0),743 }744 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(emptyClubInfo))745 return746 }747 clubInfo, err := db.GetClubInfoCountByClubId(account.ClubID)748 if err != nil {749 log.Error(err)750 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))751 return752 }753 tagIDs, pictureIDs, err := getClubTagIdsAndPictureIds(clubInfo.ClubID,754 clubInfo.Pic1ID, clubInfo.Pic2ID, clubInfo.Pic3ID, clubInfo.Pic4ID, clubInfo.Pic5ID, clubInfo.Pic6ID)755 if err != nil {756 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))757 return758 }759 clubInfoResponse :=constructClubInfoCountPost(clubInfo, tagIDs, pictureIDs)760 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(clubInfoResponse))761}762func constructClubInfoPost(clubInfo *db.ClubInfo, tagIDs []string, pictureIDs []string) *ClubInfoPost {763 clubInfoResponse := ClubInfoPost{764 ClubID: clubInfo.ClubID,765 Name: clubInfo.Name,766 Website: clubInfo.Website,767 Email: clubInfo.Email,768 GroupLink: clubInfo.GroupLink,769 VideoLink: clubInfo.VideoLink,770 Published: clubInfo.Published,771 Description: clubInfo.Description,772 LogoId: clubInfo.LogoID,773 TagIds: tagIDs,774 PictureIds: pictureIDs,775 }776 return &clubInfoResponse777}778//Returns club tag id list and picture id list.779func getClubTagIdsAndPictureIds(clubID string, picIds ...string) ([]string, []string, error) {780 //Get club tags relationships from DB781 tagRelationships, err := db.GetTagRelationshipsByClubID(clubID)782 if err != nil {783 log.Error(err)784 return nil, nil, err785 }786 //Unite tag ids from relationships787 tagIDs := make([]string, 0)788 for _, tagRelationship := range tagRelationships {789 tagIDs = append(tagIDs, tagRelationship.TagID)790 }791 //Unite non-nil pic ids792 pictureIds := make([]string, 0)793 for _, picId := range picIds {794 if picId == "" {795 break796 }797 pictureIds = append(pictureIds, picId)798 }799 return tagIDs, pictureIds, nil800}801type PageResult struct {802 CurrPage int64 `json:"curr_page"`803 PageSize int64 `json:"page_size"`804 TotalSize int64 `json:"total_size"`805 TotalPages int64 `json:"total_pages"`806 Content interface{} `json:"content"`807}808func listAllClubs(ctx *gin.Context) {809 //check admin or not810 account, err := getAdminUser(ctx)811 if err != nil {812 return813 }814 if !account.IsAdmin {815 ctx.JSON(http.StatusUnauthorized, httpserver.ConstructResponse(httpserver.NO_PERMISSION, nil))816 return817 }818 //get query params819 condition, pagination, err := getClubInfoConditionFromRequest(ctx)820 if err != nil {821 log.Error(err)822 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))823 return824 }825 //query by given condition826 clubInfos, err := db.GetClubInfoCountsByCondition(condition)827 if err != nil {828 log.Error(err)829 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))830 return831 }832 var responseInfo []ClubInfoCountPost833 for _, clubInfo := range clubInfos {834 tagIds, pictureIds, err := getClubTagIdsAndPictureIds(clubInfo.ClubID,835 clubInfo.Pic1ID, clubInfo.Pic2ID, clubInfo.Pic3ID, clubInfo.Pic4ID, clubInfo.Pic5ID, clubInfo.Pic6ID)836 if err != nil {837 log.Error(err)838 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))839 return840 }841 post := constructClubInfoCountPost(clubInfo, tagIds, pictureIds)842 responseInfo = append(responseInfo, *post)843 }844 //response when not pagination query845 if !pagination {846 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(responseInfo))847 return848 }849 //this is pagination query, get total size850 totalSize, err := db.GetClubInfoNumByCondition(condition)851 if err != nil {852 log.Error(err)853 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))854 return855 }856 pageResult := PageResult{857 CurrPage: condition.CurrPage,858 PageSize: condition.PageSize,859 TotalSize: totalSize,860 TotalPages: getTotalPages(condition.Limit, totalSize),861 Content: responseInfo,862 }863 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(pageResult))864}865func constructClubInfoCountPost(clubInfo db.ClubInfoCount, tagIDs []string, pictureIDs []string) *ClubInfoCountPost {866 clubInfoPost := ClubInfoPost{867 ClubID: clubInfo.ClubID,868 Name: clubInfo.Name,869 Website: clubInfo.Website,870 Email: clubInfo.Email,871 GroupLink: clubInfo.GroupLink,872 VideoLink: clubInfo.VideoLink,873 Published: clubInfo.Published,874 Description: clubInfo.Description,875 LogoId: clubInfo.LogoID,876 TagIds: tagIDs,877 PictureIds: pictureIDs,878 }879 post := ClubInfoCountPost{880 ClubInfoPost: clubInfoPost,881 FavouriteNum: clubInfo.FavouriteNum,882 ViewNum: clubInfo.ViewNum,883 }884 return &post885}886func getTotalPages(limit int64, totalSize int64) int64 {887 pages := totalSize / limit888 if totalSize%limit != 0 {889 pages = pages + 1890 }891 return pages892}893func tryToGetPageRequest(ctx *gin.Context) (*db.PageRequest, bool, error) {894 var pageRequest db.PageRequest895 var pagination bool896 currPageStr := ctx.Query("curr_page")897 pageSizeStr := ctx.Query("page_size")898 if currPageStr != "" && pageSizeStr != "" {899 currPage, err := strconv.ParseInt(currPageStr, 10, 64)900 if err != nil {901 return &pageRequest, pagination, err902 }903 pageSize, err := strconv.ParseInt(pageSizeStr, 10, 64)904 if err != nil {905 return &pageRequest, pagination, err906 }907 if currPage > 0 && pageSize > 0 {908 pageRequest.CurrPage = currPage909 pageRequest.PageSize = pageSize910 pageRequest.Offset = (currPage - 1) * pageSize911 pageRequest.Limit = pageSize912 pagination = true913 }914 }915 return &pageRequest, pagination, nil916}917func getAccountInfoConditionFromRequest(ctx *gin.Context) (*db.AccountInfoCondition, bool, error) {918 var condition db.AccountInfoCondition919 pageRequest, pagination, err := tryToGetPageRequest(ctx)920 if err != nil {921 return &condition, pagination, err922 }923 condition.PageRequest = *pageRequest924 //if order by create time set925 sortBy := ctx.Query("sort_by")926 if sortBy == "created_at" {927 condition.SortBy = sortBy928 }929 //if sort order set930 sortOrder := ctx.Query("sort_order")931 if sortOrder == "asc" || sortOrder == "desc" {932 condition.SortOrder = sortOrder933 }934 return &condition, pagination, nil935}936func getClubInfoConditionFromRequest(ctx *gin.Context) (*db.ClubInfoCondition, bool, error) {937 var condition db.ClubInfoCondition938 pageRequest, pagination, err := tryToGetPageRequest(ctx)939 if err != nil {940 return &condition, pagination, err941 }942 condition.PageRequest = *pageRequest943 //if published set944 published := ctx.Query("published")945 if published == "true" || published == "false" {946 condition.Published = published947 }948 //if order by create time set949 sortBy := ctx.Query("sort_by")950 if sortBy == "created_at" {951 condition.SortBy = sortBy952 }953 //if sort order set954 sortOrder := ctx.Query("sort_order")955 if sortOrder == "asc" || sortOrder == "desc" {956 condition.SortOrder = sortOrder957 }958 return &condition, pagination, nil959}960func getAccountByUserId(ctx *gin.Context) {961 //check admin or not962 account, err := getAdminUser(ctx)963 if err != nil {964 return965 }966 if !account.IsAdmin {967 ctx.JSON(http.StatusUnauthorized, httpserver.ConstructResponse(httpserver.NO_PERMISSION, nil))968 return969 }970 userId := ctx.Param("userId")971 account, err = db.GetAccountByUserId(userId)972 if gorm.IsRecordNotFoundError(err) {973 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.NOT_FOUND, nil))974 return975 }976 if err != nil {977 log.Error(err)978 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))979 return980 }981 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(account))982}983func listAllAccounts(ctx *gin.Context) {984 //check admin or not985 account, err := getAdminUser(ctx)986 if err != nil {987 return988 }989 if !account.IsAdmin {990 ctx.JSON(http.StatusUnauthorized, httpserver.ConstructResponse(httpserver.NO_PERMISSION, nil))991 return992 }993 //query account info994 condition, pagination, err := getAccountInfoConditionFromRequest(ctx)995 if err != nil {996 log.Error(err)997 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))998 return999 }1000 accounts, err := db.GetAllAccountInfoByCondition(condition)1001 if err != nil {1002 log.Error(err)1003 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))1004 return1005 }1006 if !pagination {1007 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(accounts))1008 return1009 }1010 //this is a pagination query1011 totalSize, err := db.GetTotalAccountNum()1012 if err != nil {1013 log.Error(err)1014 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))1015 return1016 }1017 pageResult := PageResult{1018 CurrPage: condition.CurrPage,1019 PageSize: condition.PageSize,1020 TotalSize: totalSize,1021 TotalPages: getTotalPages(condition.Limit, totalSize),1022 Content: accounts,1023 }1024 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(pageResult))1025}1026// Generate a new auth string1027func genAuthString() string {1028 h := sha512.New()1029 h.Write([]byte(uuid.New().String()))1030 str1 := hex.EncodeToString(h.Sum(nil))1031 h.Write([]byte(uuid.New().String()))1032 str2 := hex.EncodeToString(h.Sum(nil))1033 return str1 + str21034}1035type NewClubAccountPost struct {1036 Email string `json:"email"`1037 PhoneNum string `json:"phone_num"`1038 Note string `json:"note"`1039}1040//creates a club account and its club info.1041func createNewClubAccount(ctx *gin.Context) {1042 //check admin or not1043 account, err := getAdminUser(ctx)1044 if err != nil {1045 return1046 }1047 if !account.IsAdmin {1048 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.NO_PERMISSION, nil))1049 return1050 }1051 //obtain and simply check request body param1052 newClub := new(NewClubAccountPost)1053 if err := ctx.ShouldBindJSON(newClub); err != nil {1054 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))1055 return1056 }1057 if len(newClub.Email) == 0 || len(newClub.PhoneNum) == 0 || len(newClub.Note) == 0 || len(newClub.Note) > 200 {1058 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))1059 return1060 }1061 //construct account and club info1062 clubAccount := db.AdminAccount{1063 AccountID: uuid.New().String(),1064 AuthString: genAuthString(),1065 ClubID: uuid.New().String(),1066 Email: newClub.Email,1067 PhoneNum: newClub.PhoneNum,1068 Note: newClub.Note,1069 IsAdmin: false,1070 }1071 clubInfo := db.ClubInfo{1072 ClubID: clubAccount.ClubID,1073 }1074 //create transaction to insert account and club info1075 txDb := db.DB.Begin()1076 err = clubAccount.Insert(txDb)1077 if err != nil {1078 txDb.Rollback()1079 log.Error(err)1080 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))1081 return1082 }1083 err = clubInfo.Insert(txDb)1084 if err != nil {1085 txDb.Rollback()1086 log.Error(err)1087 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))1088 return1089 }1090 txDb.Commit()1091 //response account created1092 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(clubAccount))1093}1094func Pong(c *gin.Context) {1095 c.JSON(1096 http.StatusOK,1097 httpserver.ConstructResponse(httpserver.SUCCESS, gin.H{1098 "message": "pong",1099 }))1100}1101type LoginPost struct {1102 AuthToken string `json:"auth_token"`1103}1104// Handles Admin Login1105func Login(c *gin.Context) {1106 loginPost := new(LoginPost)1107 if err := c.ShouldBindJSON(loginPost); err != nil {1108 c.JSON(http.StatusUnauthorized, httpserver.ConstructResponse(httpserver.AUTH_FAILED, nil))1109 log.Print(err)1110 return1111 }1112 var Account db.AdminAccount1113 if err := db.DB.Where("auth_string = ?", loginPost.AuthToken).First(&Account).Error; err != nil {1114 c.JSON(http.StatusUnauthorized, httpserver.ConstructResponse(httpserver.AUTH_FAILED, nil))1115 log.Print(err)1116 return1117 }1118 // Save the username in the session1119 session := sessions.Default(c)1120 session.Set(USER, Account)1121 if err := session.Save(); err != nil {1122 c.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))1123 return1124 }1125 c.JSON(http.StatusOK, httpserver.SuccessResponse(Account))1126}1127type ClubInfoPost struct {1128 ClubID string `json:"club_id" binding:"required"`1129 Name string `json:"name"`1130 Website string `json:"website"`1131 Email string `json:"email"`1132 GroupLink string `json:"group_link"`1133 VideoLink string `json:"video_link"`1134 Published bool `json:"published"`1135 Description string `json:"description"`1136 LogoId string `json:"logo_id"`1137 TagIds []string `json:"tag_ids"`1138 PictureIds []string `json:"picture_ids"`1139}1140type ClubInfoCountPost struct {1141 ClubInfoPost1142 FavouriteNum int64 `json:"favourite_num"`1143 ViewNum int64 `json:"view_num"`1144}1145const (1146 CLUB_NAME_MAX_LEN = 1001147 CLUB_PIC_MAX_NUM = 61148 CLUB_TAG_MAX_NUM = 41149)1150//Club user updates their club info.1151func updateClubInfo(ctx *gin.Context) {1152 account, err := getAdminUser(ctx)1153 if err != nil {1154 return1155 }1156 //obtain and check request params1157 var clubInfoPost ClubInfoPost1158 if err := ctx.ShouldBindJSON(&clubInfoPost); err != nil {1159 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))1160 return1161 }1162 if len(clubInfoPost.Name) == 0 || len(clubInfoPost.Name) > CLUB_NAME_MAX_LEN {1163 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))1164 return1165 }1166 if len(clubInfoPost.PictureIds) > CLUB_PIC_MAX_NUM {1167 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.CLUB_PIC_NUM_ABOVE_LIMIT, nil))1168 return1169 }1170 if len(clubInfoPost.TagIds) > CLUB_TAG_MAX_NUM {1171 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.CLUB_TAG_NUM_ABOVE_LIMIT, nil))1172 return1173 }1174 if len(clubInfoPost.Website) > 300 {1175 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.WEB_SITE_TOO_LONG, nil))1176 return1177 }1178 if len(clubInfoPost.Email) > 100 {1179 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.EMAIL_TOO_LONG, nil))1180 return1181 }1182 if len(clubInfoPost.Description) > 4000 {1183 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.DESC_TOO_LONG, nil))1184 return1185 }1186 if len(clubInfoPost.VideoLink) > 300 {1187 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.VIDEO_LINK_TOO_LONG, nil))1188 return1189 }1190 if len(clubInfoPost.GroupLink) > 150 {1191 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))1192 return1193 }1194 // Club tags1195 if len(clubInfoPost.TagIds) > 0 {1196 tags, err := db.GetClubTagsByTagIds(clubInfoPost.TagIds)1197 if err != nil {1198 log.Error(err)1199 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))1200 return1201 }1202 // Check for invalid tag IDs1203 if len(clubInfoPost.TagIds) != len(tags) {1204 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))1205 return1206 }1207 }1208 log.Println(clubInfoPost.PictureIds)1209 // Club picture upload1210 if len(clubInfoPost.PictureIds) > 0 {1211 dbPictureIDs, err := db.GetAccPictureIDS(account.AccountID)1212 dbPictureIDsSet := set.NewSet()1213 for _, accPic := range dbPictureIDs {1214 dbPictureIDsSet.Add(accPic.PictureID)1215 }1216 if err != nil {1217 log.Error(err)1218 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))1219 return1220 }1221 // Check for invalid IDs1222 for _, pid := range clubInfoPost.PictureIds {1223 if !dbPictureIDsSet.Contains(pid) {1224 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, "does not contain this picture"))1225 return1226 }1227 }1228 }1229 // Construct club information1230 clubInfo := db.ClubInfo{1231 ClubID: clubInfoPost.ClubID,1232 Name: clubInfoPost.Name,1233 Website: clubInfoPost.Website,1234 Email: clubInfoPost.Email,1235 GroupLink: clubInfoPost.GroupLink,1236 VideoLink: clubInfoPost.VideoLink,1237 Published: clubInfoPost.Published,1238 Description: clubInfoPost.Description,1239 LogoID: clubInfoPost.LogoId,1240 }1241 for idx, pid := range clubInfoPost.PictureIds {1242 // TODO 最好不要这么写,现在为了方便先这样1243 reflect.ValueOf(&clubInfo).Elem().FieldByName(fmt.Sprintf("Pic%dID", idx+1)).SetString(pid)1244 }1245 txDb := db.DB.Begin()1246 err = clubInfo.Update(txDb)1247 if err != nil {1248 log.Error(err)1249 txDb.Rollback()1250 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))1251 return1252 }1253 // Update club tags relationship1254 if len(clubInfoPost.TagIds) > 0 {1255 // Clean up old associations1256 err := db.CleanAllTags(txDb, clubInfoPost.ClubID)1257 if err != nil {1258 log.Error(err)1259 txDb.Rollback()1260 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))1261 return1262 }1263 // Then insert latest relationship1264 for _, tagId := range clubInfoPost.TagIds {1265 relationship := db.ClubTagRelationship{1266 ClubID: clubInfo.ClubID,1267 TagID: tagId,1268 }1269 err := relationship.Insert(txDb)1270 if err != nil {1271 log.Error(err)1272 txDb.Rollback()1273 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))1274 return1275 }1276 }1277 }1278 txDb.Commit()1279 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(nil))1280}1281type UploadPicResponse struct {1282 Pid string `json:"pid"`1283}1284// Upload a picture and return an ID1285func uploadSinglePicture(ctx *gin.Context) {1286 account, err := getAdminUser(ctx)1287 if err != nil {1288 return1289 }1290 file, err := ctx.FormFile("file")1291 if err != nil {1292 log.Error(err)1293 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.INVALID_PARAMS, nil))1294 return1295 }1296 // ensures what's uploaded is a picture1297 if !strings.HasSuffix(file.Filename, ".jpg") && !strings.HasSuffix(file.Filename, ".jpeg") {1298 log.Println(file.Filename)1299 log.Errorf("Uploaded file is %v. The extension does noe match jpg ir jpeg", file.Filename)1300 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.UPLOAD_TYPE_NOT_SUPPORTED, nil))1301 return1302 }1303 MaxFileSize := int64(1 << 20)1304 // Check file size limit1305 if file.Size > MaxFileSize {1306 log.Errorf("File size is %v MB > than 1MB", file.Size/1<<20)1307 ctx.JSON(http.StatusBadRequest, httpserver.ConstructResponse(httpserver.PIC_TOO_LARGE, nil))1308 return1309 }1310 fileUUID := uuid.New().String()1311 fileName := fileUUID + path.Ext(file.Filename)1312 basePath := path.Join(globalConfig.General.PictureStoragePath, fileName)1313 err = ctx.SaveUploadedFile(file, basePath)1314 if err != nil {1315 log.Error(err)1316 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))1317 return1318 }1319 // Sanity check done. Save picture info into db,1320 pictureEntry := db.AccountPicture{1321 AccountID: account.AccountID,1322 PictureID: fileUUID,1323 PictureName: fileName,1324 }1325 err = db.DB.Create(&pictureEntry).Error1326 if err != nil {1327 log.Error(err)1328 ctx.JSON(http.StatusInternalServerError, httpserver.ConstructResponse(httpserver.SYSTEM_ERROR, nil))1329 return1330 }1331 ctx.JSON(http.StatusOK, httpserver.SuccessResponse(UploadPicResponse{Pid: fileUUID}))1332}...

Full Screen

Full Screen

server_test.go

Source:server_test.go Github

copy

Full Screen

...23 ap.X = &x24 ap.Y = &y25 return nil26}27func Sum(params json.RawMessage) (interface{}, *ErrorObject) {28 p := new(SumParams)29 if err := ParseParams(params, p); err != nil {30 return nil, err31 }32 if p.X == nil || p.Y == nil {33 return nil, &ErrorObject{34 Code: InvalidParamsCode,35 Message: InvalidParamsMsg,36 Data: "exactly two integers are required",37 }38 }39 return *p.X + *p.Y, nil40}41type SubtractParams struct {42 X *float64 `json:"minuend"`43 Y *float64 `json:"subtrahend"`44}45func (ap *SubtractParams) FromPositional(params []interface{}) error {46 if len(params) != 2 {47 return errors.New(fmt.Sprintf("exactly two integers are required"))48 }49 x := params[0].(float64)50 y := params[1].(float64)51 ap.X = &x52 ap.Y = &y53 return nil54}55func Subtract(params json.RawMessage) (interface{}, *ErrorObject) {56 p := new(SubtractParams)57 if err := ParseParams(params, p); err != nil {58 return nil, err59 }60 if *p.X == 999.0 && *p.Y == 999.0 {61 return nil, &ErrorObject{62 Code: -32001,63 Message: ServerErrorMsg,64 Data: "Mock error",65 }66 }67 if p.X == nil || p.Y == nil {68 return nil, &ErrorObject{69 Code: InvalidParamsCode,70 Message: InvalidParamsMsg,71 Data: "exactly two integers are required",72 }73 }74 return *p.X - *p.Y, nil75}76func init() {77 var wg sync.WaitGroup78 wg.Add(1)79 go func() { // subtract method remote server80 s := NewServer(":31501", "/api/v2/rpc", nil)81 s.Register("subtract", Method{Method: Subtract})82 s.Start()83 }()84 go func() { // primary server with subtract remote server proxy85 s := NewServer(":31500", "/api/v1/rpc", map[string]string{86 "X-Test-Header": "some-test-value",87 })88 s.Register("sum", Method{Method: Sum})89 s.Register("update", Method{Method: func(params json.RawMessage) (interface{}, *ErrorObject) { return nil, nil }})90 s.Register("foobar", Method{Method: func(params json.RawMessage) (interface{}, *ErrorObject) { return nil, nil }})91 s.Start()92 }()93 go func() {94 for {95 body := `{"jsonrpc": "2.0", "method": "jrpc2.register", "params": ["subtract", "http://localhost:31501/api/v2/rpc"]}`96 buf := bytes.NewBuffer([]byte(body))97 _, err := http.Post("http://localhost:31500/api/v1/rpc", "application/json", buf)98 if err != nil {99 time.Sleep(1 * time.Second)100 continue101 }102 break103 }104 wg.Done()105 }()106 wg.Wait()107}108func TestResponseHeaders(t *testing.T) {109 buf := bytes.NewBuffer([]byte(`{}`))110 resp, err := http.Post("http://localhost:31500/api/v1/rpc", "application/json", buf)111 if err != nil {112 t.Fatal(err)113 }114 defer resp.Body.Close()115 if v := resp.Header.Get("X-Test-Header"); v != "some-test-value" {116 t.Fatal("got unexpected X-Test-Header value")117 }118}119func TestRpcCallWithPositionalParamters(t *testing.T) {120 table := []struct {121 Body string122 Jsonrpc string `json:"jsonrpc"`123 Result int `json:"result"`124 Id int `json:"id"`125 }{126 {`{"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1}`, "2.0", 19, 1},127 {`{"jsonrpc": "2.0", "method": "subtract", "params": [23, 42], "id": 2}`, "2.0", -19, 2},128 }129 for _, tc := range table {130 var result struct {131 Jsonrpc string `json:"jsonrpc"`132 Result int `json:"result"`133 Error interface{} `json:"error"`134 Id int `json:"id"`135 }136 buf := bytes.NewBuffer([]byte(tc.Body))137 resp, err := http.Post("http://localhost:31500/api/v1/rpc", "application/json", buf)138 if err != nil {139 t.Fatal(err)140 }141 rdr := bufio.NewReader(resp.Body)142 dec := json.NewDecoder(rdr)143 dec.Decode(&result)144 if result.Error != nil {145 t.Fatal("Expected error to be nil")146 }147 if result.Jsonrpc != tc.Jsonrpc {148 t.Fatal("Invalid jsonrpc member value")149 }150 if result.Result != tc.Result {151 t.Fatalf("Expected result to be %d", tc.Result)152 }153 if result.Id != tc.Id {154 t.Fatalf("Expected id to be %d", tc.Id)155 }156 }157}158func TestRpcCallWithPositionalParamtersError(t *testing.T) {159 var result struct {160 Jsonrpc string `json:"jsonrpc"`161 Result interface{} `json:"result"`162 Err ErrorObject `json:"error"`163 Id int `json:"id"`164 }165 body := `{"jsonrpc": "2.0", "method": "subtract", "params": [999, 999], "id": 1}`166 buf := bytes.NewBuffer([]byte(body))167 resp, err := http.Post("http://localhost:31500/api/v1/rpc", "application/json", buf)168 if err != nil {169 t.Fatal(err)170 }171 rdr := bufio.NewReader(resp.Body)172 dec := json.NewDecoder(rdr)173 dec.Decode(&result)174 if result.Result != nil {175 t.Fatal("Expected result to be nil")176 }177 if result.Err.Code != -32001 {178 t.Fatal("Expected code to be -32001")179 }180 if result.Err.Message != "Server error" {181 t.Fatal("Expected message to be 'Server error'")182 }183 if result.Err.Data != "Mock error" {184 t.Fatal("Expected data to be 'Mock error'")185 }186 if result.Id != 1 {187 t.Fatal("Expected id to be 1")188 }189}190func TestRpcCallWithNamedParameters(t *testing.T) {191 table := []struct {192 Body string193 Jsonrpc string `json:"jsonrpc"`194 Result int `json:"result"`195 Id int `json:"id"`196 }{197 {`{"jsonrpc": "2.0", "method": "subtract", "params": {"subtrahend": 23, "minuend": 42}, "id": 3}`, "2.0", 19, 3},198 {`{"jsonrpc": "2.0", "method": "subtract", "params": {"minuend": 42, "subtrahend": 23}, "id": 4}`, "2.0", 19, 4},199 }200 for _, tc := range table {201 var result struct {202 Jsonrpc string `json:"jsonrpc"`203 Result int `json:"result"`204 Error interface{} `json:"error"`205 Id int `json:"id"`206 }207 buf := bytes.NewBuffer([]byte(tc.Body))208 resp, err := http.Post("http://localhost:31500/api/v1/rpc", "application/json", buf)209 if err != nil {210 t.Fatal(err)211 }212 rdr := bufio.NewReader(resp.Body)213 dec := json.NewDecoder(rdr)214 dec.Decode(&result)215 if result.Error != nil {216 t.Fatal("Expected error to be nil")217 }218 if result.Jsonrpc != tc.Jsonrpc {219 t.Fatal("Invalid jsonrpc member value")220 }221 if result.Result != tc.Result {222 t.Fatalf("Expected result to be %d", tc.Result)223 }224 if result.Id != tc.Id {225 t.Fatalf("Expected id to be %d", tc.Id)226 }227 }228}229func TestNotification(t *testing.T) {230 table := []string{231 `{"jsonrpc": "2.0", "method": "update", "params": [1,2,3,4,5]}`,232 `{"jsonrpc": "2.0", "method": "foobar"}`,233 }234 for _, body := range table {235 buf := bytes.NewBuffer([]byte(body))236 resp, err := http.Post("http://localhost:31500/api/v1/rpc", "application/json", buf)237 if err != nil {238 t.Fatal(err)239 }240 rdr := bufio.NewReader(resp.Body)241 data, err := rdr.ReadBytes('\b')242 if len(data) > 0 {243 t.Fatal("Expected notification to return no response body")244 }245 }246}247func TestCallOfNotExistentMethod(t *testing.T) {248 var result struct {249 Jsonrpc string `json:"jsonrpc"`250 Err ErrorObject `json:"error"`251 Result interface{} `json:"result"`252 Id int `json:"id"`253 }254 body := `{"jsonrpc": "2.0", "method": "fooba", "id": "1"}`255 buf := bytes.NewBuffer([]byte(body))256 resp, err := http.Post("http://localhost:31500/api/v1/rpc", "application/json", buf)257 if err != nil {258 t.Fatal(err)259 }260 rdr := bufio.NewReader(resp.Body)261 dec := json.NewDecoder(rdr)262 dec.Decode(&result)263 if result.Result != nil {264 t.Fatal("expected result to be nil")265 }266 if result.Err.Code != -32601 {267 t.Fatal("expected error code -32601")268 }269 if result.Err.Message != "Method not found" {270 t.Fatal("expected message to be 'Message not found'")271 }272}273func TestCallWithInvalidJSON(t *testing.T) {274 var result struct {275 Jsonrpc string `json:"jsonrpc"`276 Err ErrorObject `json:"error"`277 Result interface{} `json:"result"`278 Id int `json:"id"`279 }280 body := `{"jsonrpc": "2.0", "method": "foobar, "params": "bar", "baz]`281 buf := bytes.NewBuffer([]byte(body))282 resp, err := http.Post("http://localhost:31500/api/v1/rpc", "application/json", buf)283 if err != nil {284 t.Fatal(err)285 }286 rdr := bufio.NewReader(resp.Body)287 dec := json.NewDecoder(rdr)288 dec.Decode(&result)289 if result.Result != nil {290 t.Fatal("expected result to be nil")291 }292 if result.Err.Code != -32700 {293 t.Fatal("expected error code -32700")294 }295 if result.Err.Message != "Parse error" {296 t.Fatal("expected message to be 'Parse error'")297 }298}299func TestCallWithInvalidRequestObject(t *testing.T) {300 var result struct {301 Jsonrpc string `json:"jsonrpc"`302 Err ErrorObject `json:"error"`303 Result interface{} `json:"result"`304 Id int `json:"id"`305 }306 body := `{"jsonrpc": "2.0", "method": 1, "params": "bar"}`307 buf := bytes.NewBuffer([]byte(body))308 resp, err := http.Post("http://localhost:31500/api/v1/rpc", "application/json", buf)309 if err != nil {310 t.Fatal(err)311 }312 rdr := bufio.NewReader(resp.Body)313 dec := json.NewDecoder(rdr)314 dec.Decode(&result)315 if result.Result != nil {316 t.Fatal("expected result to be nil")317 }318 if result.Err.Code != -32600 {319 t.Fatal("expected error code -32600")320 }321 if result.Err.Message != "Invalid Request" {322 t.Fatal("expected message to be 'Invalid Request'")323 }324}325func TestBatchCallWithInvalidJSON(t *testing.T) {326 var result struct {327 Jsonrpc string `json:"jsonrpc"`328 Err ErrorObject `json:"error"`329 Result interface{} `json:"result"`330 Id int `json:"id"`331 }332 body := `[333 {"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"},334 {"jsonrpc": "2.0", "method"335 ]`336 buf := bytes.NewBuffer([]byte(body))337 resp, err := http.Post("http://localhost:31500/api/v1/rpc", "application/json", buf)338 if err != nil {339 t.Fatal(err)340 }341 rdr := bufio.NewReader(resp.Body)342 dec := json.NewDecoder(rdr)343 dec.Decode(&result)344 if result.Result != nil {345 t.Fatal("expected result to be nil")346 }347 if result.Err.Code != -32700 {348 t.Fatal("expected error code -32700")349 }350 if result.Err.Message != "Parse error" {351 t.Fatal("expected message to be 'Parse error'")352 }353}354func TestBatchCallWithAnEmptyArray(t *testing.T) {355 var result struct {356 Jsonrpc string `json:"jsonrpc"`357 Err ErrorObject `json:"error"`358 Result interface{} `json:"result"`359 Id int `json:"id"`360 }361 body := `[]`362 buf := bytes.NewBuffer([]byte(body))363 resp, err := http.Post("http://localhost:31500/api/v1/rpc", "application/json", buf)364 if err != nil {365 t.Fatal(err)366 }367 rdr := bufio.NewReader(resp.Body)368 dec := json.NewDecoder(rdr)369 dec.Decode(&result)370 if result.Result != nil {371 t.Fatal("expected result to be nil")372 }373 if result.Err.Code != -32600 {374 t.Fatal("expected error code -32600")375 }376 if result.Err.Message != "Invalid Request" {377 t.Fatal("expected message to be 'Invalid Request'")378 }379}380func TestCallWithAnInvalidBatch(t *testing.T) {381 var results []struct {382 Jsonrpc string `json:"jsonrpc"`383 Err ErrorObject `json:"error"`384 Result interface{} `json:"result"`385 Id int `json:"id"`386 }387 body := `[]`388 buf := bytes.NewBuffer([]byte(body))389 resp, err := http.Post("http://localhost:31500/api/v1/rpc", "application/json", buf)390 if err != nil {391 t.Fatal(err)392 }393 rdr := bufio.NewReader(resp.Body)394 dec := json.NewDecoder(rdr)395 dec.Decode(&results)396 for _, result := range results {397 if result.Result != nil {...

Full Screen

Full Screen

json.go

Source:json.go Github

copy

Full Screen

...112 if binKind == 0 {113 return binData, nil114 }115 if binKind < 0 || binKind > 255 {116 return nil, fmt.Errorf("invalid type in binary object: %s", data)117 }118 return Binary{Kind: byte(binKind), Data: binData}, nil119}120func jencBinarySlice(v interface{}) ([]byte, error) {121 in := v.([]byte)122 out := make([]byte, base64.StdEncoding.EncodedLen(len(in)))123 base64.StdEncoding.Encode(out, in)124 return fbytes(`{"$binary":"%s","$type":"0x0"}`, out), nil125}126func jencBinaryType(v interface{}) ([]byte, error) {127 in := v.(Binary)128 out := make([]byte, base64.StdEncoding.EncodedLen(len(in.Data)))129 base64.StdEncoding.Encode(out, in.Data)130 return fbytes(`{"$binary":"%s","$type":"0x%x"}`, out, in.Kind), nil131}132const jdateFormat = "2006-01-02T15:04:05.999Z"133func jdecDate(data []byte) (interface{}, error) {134 var v struct {135 S string `json:"$date"`136 Func struct {137 S string138 } `json:"$dateFunc"`139 }140 _ = jdec(data, &v)141 if v.S == "" {142 v.S = v.Func.S143 }144 if v.S != "" {145 for _, format := range []string{jdateFormat, "2006-01-02"} {146 t, err := time.Parse(format, v.S)147 if err == nil {148 return t, nil149 }150 }151 return nil, fmt.Errorf("cannot parse date: %q", v.S)152 }153 var vn struct {154 Date struct {155 N int64 `json:"$numberLong,string"`156 } `json:"$date"`157 Func struct {158 S int64159 } `json:"$dateFunc"`160 }161 err := jdec(data, &vn)162 if err != nil {163 return nil, fmt.Errorf("cannot parse date: %q", data)164 }165 n := vn.Date.N166 if n == 0 {167 n = vn.Func.S168 }169 return time.Unix(n/1000, n%1000*1e6).UTC(), nil170}171func jencDate(v interface{}) ([]byte, error) {172 t := v.(time.Time)173 return fbytes(`{"$date":%q}`, t.Format(jdateFormat)), nil174}175func jdecTimestamp(data []byte) (interface{}, error) {176 var v struct {177 Func struct {178 T int32 `json:"t"`179 I int32 `json:"i"`180 } `json:"$timestamp"`181 }182 err := jdec(data, &v)183 if err != nil {184 return nil, err185 }186 return MongoTimestamp(uint64(v.Func.T)<<32 | uint64(uint32(v.Func.I))), nil187}188func jencTimestamp(v interface{}) ([]byte, error) {189 ts := uint64(v.(MongoTimestamp))190 return fbytes(`{"$timestamp":{"t":%d,"i":%d}}`, ts>>32, uint32(ts)), nil191}192func jdecRegEx(data []byte) (interface{}, error) {193 var v struct {194 Regex string `json:"$regex"`195 Options string `json:"$options"`196 }197 err := jdec(data, &v)198 if err != nil {199 return nil, err200 }201 return RegEx{v.Regex, v.Options}, nil202}203func jencRegEx(v interface{}) ([]byte, error) {204 re := v.(RegEx)205 type regex struct {206 Regex string `json:"$regex"`207 Options string `json:"$options"`208 }209 return json.Marshal(regex{re.Pattern, re.Options})210}211func jdecObjectId(data []byte) (interface{}, error) {212 var v struct {213 Id string `json:"$oid"`214 Func struct {215 Id string216 } `json:"$oidFunc"`217 }218 err := jdec(data, &v)219 if err != nil {220 return nil, err221 }222 if v.Id == "" {223 v.Id = v.Func.Id224 }225 return ObjectIdHex(v.Id), nil226}227func jencObjectId(v interface{}) ([]byte, error) {228 return fbytes(`{"$oid":"%s"}`, v.(ObjectId).Hex()), nil229}230func jdecDBRef(data []byte) (interface{}, error) {231 // TODO Support unmarshaling $ref and $id into the input value.232 var v struct {233 Obj map[string]interface{} `json:"$dbrefFunc"`234 }235 // TODO Fix this. Must not be required.236 v.Obj = make(map[string]interface{})237 err := jdec(data, &v)238 if err != nil {239 return nil, err240 }241 return v.Obj, nil242}243func jdecNumberLong(data []byte) (interface{}, error) {244 var v struct {245 N int64 `json:"$numberLong,string"`246 Func struct {247 N int64 `json:",string"`248 } `json:"$numberLongFunc"`249 }250 var vn struct {251 N int64 `json:"$numberLong"`252 Func struct {253 N int64254 } `json:"$numberLongFunc"`255 }256 err := jdec(data, &v)257 if err != nil {258 err = jdec(data, &vn)259 v.N = vn.N260 v.Func.N = vn.Func.N261 }262 if err != nil {263 return nil, err264 }265 if v.N != 0 {266 return v.N, nil267 }268 return v.Func.N, nil269}270func jencNumberLong(v interface{}) ([]byte, error) {271 n := v.(int64)272 f := `{"$numberLong":"%d"}`273 if n <= 1<<53 {274 f = `{"$numberLong":%d}`275 }276 return fbytes(f, n), nil277}278func jencInt(v interface{}) ([]byte, error) {279 n := v.(int)280 f := `{"$numberLong":"%d"}`281 if n <= 1<<53 {282 f = `%d`283 }284 return fbytes(f, n), nil285}286func jdecMinKey(data []byte) (interface{}, error) {287 var v struct {288 N int64 `json:"$minKey"`289 }290 err := jdec(data, &v)291 if err != nil {292 return nil, err293 }294 if v.N != 1 {295 return nil, fmt.Errorf("invalid $minKey object: %s", data)296 }297 return MinKey, nil298}299func jdecMaxKey(data []byte) (interface{}, error) {300 var v struct {301 N int64 `json:"$maxKey"`302 }303 err := jdec(data, &v)304 if err != nil {305 return nil, err306 }307 if v.N != 1 {308 return nil, fmt.Errorf("invalid $maxKey object: %s", data)309 }310 return MaxKey, nil311}312func jencMinMaxKey(v interface{}) ([]byte, error) {313 switch v.(orderKey) {314 case MinKey:315 return []byte(`{"$minKey":1}`), nil316 case MaxKey:317 return []byte(`{"$maxKey":1}`), nil318 }319 panic(fmt.Sprintf("invalid $minKey/$maxKey value: %d", v))320}321func jdecUndefined(data []byte) (interface{}, error) {322 var v struct {323 B bool `json:"$undefined"`324 }325 err := jdec(data, &v)326 if err != nil {327 return nil, err328 }329 if !v.B {330 return nil, fmt.Errorf("invalid $undefined object: %s", data)331 }332 return Undefined, nil333}334func jencUndefined(v interface{}) ([]byte, error) {335 return []byte(`{"$undefined":true}`), nil336}...

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import (2type Person struct {3}4func main() {5 p1 := Person{"James", "Bond", 20}6 bs, err := json.Marshal(p1)7 if err != nil {8 fmt.Println(err)9 }10 fmt.Println(string(bs))11}12{"First":"James","Last":"Bond","Age":20}13import (14type Person struct {15}16func main() {17 p1 := Person{"James", "Bond", 20}18 bs, err := json.Marshal(p1)19 if err != nil {20 fmt.Println(err)21 }22 fmt.Println(string(bs))23}24{"First":"James","Last":"Bond","Age":20}25import (26type Person struct {27}28func main() {29 p1 := Person{"James", "Bond", 20}30 bs, err := json.MarshalIndent(p1, "", "\t")31 if err != nil {32 fmt.Println(err)33 }34 fmt.Println(string(bs))35}36{37}38import (39type Person struct {40}41func main() {42 bs := []byte(`{"First":"James","Last":"Bond","Age":20}`)43 json.Unmarshal(bs, &p1)44 fmt.Println("The First Name is", p1.First)45 fmt.Println("The Last Name is", p1.Last)46 fmt.Println("The Age is", p1.Age)47}

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import (2type Person struct {3}4func main() {5 p1 := Person{"James", "Bond", 20, 007}6 bs, _ := json.Marshal(p1)7 fmt.Println(bs)8 fmt.Printf("%T9 fmt.Println(string(bs))10}11{"First":"James","Last":"Bond","Age":20}12import (13type Person struct {14}15func main() {16 p1 := Person{"James", "Bond", 20, 007}17 bs, err := json.Marshal(p1)18 if err != nil {19 fmt.Println(err)20 }21 fmt.Println(bs)22 fmt.Printf("%T23 fmt.Println(string(bs))24}25{"First":"James","Last":"Bond","Age":20}26import (27type Person struct {28}29func main() {30 p1 := Person{"James", "Bond", 20, 007}31 bs, err := json.Marshal(p1)32 if err != nil {33 fmt.Println(err)34 }

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1func main() {2 var jsonBlob = []byte(`{"Name": "Platypus", "Order": "Monotremata"}`)3 err := json.Unmarshal(jsonBlob, &animal)4 if err != nil {5 fmt.Println("error:", err)6 }7 fmt.Printf("%+v8}9func main() {10 var jsonBlob = []byte(`{"Name": "Platypus", "Order": "Monotremata"}`)11 err := json.Unmarshal(jsonBlob, &animal)12 if err != nil {13 fmt.Println("error:", err.Error())14 }15 fmt.Printf("%+v16}17func main() {18 var jsonBlob = []byte(`{"Name": "Platypus", "Order": "Monotremata"}`)19 err := json.Unmarshal(jsonBlob, &animal)20 if err != nil {21 fmt.Println("error:", err.Error())22 }23 fmt.Printf("%+v24}25func main() {26 var jsonBlob = []byte(`{"Name": "Platypus", "Order": "Monotremata"}`)27 err := json.Unmarshal(jsonBlob, &animal)28 if err != nil {29 fmt.Println("error:", err.Error())30 }31 fmt.Printf("%+v32}33func main() {34 var jsonBlob = []byte(`{"Name": "Platypus", "Order": "Monotremata"}`)35 err := json.Unmarshal(jsonBlob, &animal)36 if err != nil {37 fmt.Println("error:",

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 var jsonBlob = []byte(`[4 {"Name": "Platypus", "Order": "Monotremata"},5 {"Name": "Quoll", "Order": "Dasyuromorphia"}6 type Animal struct {7 }8 err := json.Unmarshal(jsonBlob, &animals)9 if err != nil {10 fmt.Println("error:", err)11 }12 fmt.Printf("%+v", animals)13}14[{Name: Platypus Order: Monotremata} {Name: Quoll Order: Dasyuromorphia}]

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import (2func main() {3var data = []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)4var f interface{}5err := json.Unmarshal(data, &f)6if err != nil {7fmt.Println(err)8}9fmt.Println(f)10}11import (12func main() {13var data = []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)14err := json.Unmarshal(data, &f)15if err != nil {16fmt.Println(err)17}18fmt.Println(f)19}20{Wednesday 6 [Gomez Morticia]}21func Marshal(v interface{}) ([]byte, error)22import (23func main() {24var str = []string{"apple", "peach", "pear"}25b, err := json.Marshal(str)26if err != nil {27fmt.Println(err)28}29fmt.Println(string(b))30}

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import (2func main() {3    var data map[string]interface{}4    input := `{"Name": "Wednesday", "Age": 6, "Parents": ["Gomez", "Morticia"]}`5    err := json.Unmarshal([]byte(input), &data)6    if err != nil {7        fmt.Println("Error:", err)8    }9    fmt.Println(data)10}11import (12func main() {13    var data map[string]interface{}14    input := `{"Name": "Wednesday", "Age": 6, "Parents": ["Gomez", "Morticia"]}`15    err := json.Unmarshal([]byte(input), &data)16    if err != nil {17        fmt.Println("Error:", err.Error())18    }19    fmt.Println(data)20}21import (22func main() {23    var data map[string]interface{}24    input := `{"Name": "Wednesday", "Age": 6, "Parents": ["Gomez", "Morticia"]}`25    err := json.Unmarshal([]byte(input), &data)26    if err != nil {27        fmt.Println("Error:", err.Error())28    }29    fmt.Println(data)30}31import (32func main() {33    var data map[string]interface{}34    input := `{"Name": "Wednesday", "Age": 6, "Parents": ["Gomez", "Morticia"]}`35    err := json.Unmarshal([]byte(input), &data)36    if err != nil {37        fmt.Println("Error:", err

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import (2type Employee struct {3}4func main() {5 emp := Employee{6 }7 jsonString, err := json.Marshal(emp)8 if err != nil {9 fmt.Println(err)10 }11 fmt.Println(string(jsonString))12}13{"Name":"John","Age":30}14import (15type Employee struct {16}17func main() {18 jsonString := []byte(`{19 }`)20 err := json.Unmarshal(jsonString, &emp)21 if err != nil {22 fmt.Println(err)23 }24 fmt.Println(emp)25}26{John 30}27import (28type Employee struct {29}30func main() {31 emp := Employee{

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import (2type Student struct {3}4func main() {5 s := Student{"John", 24}6 b, err := json.Marshal(s)7 if err != nil {8 fmt.Println(err)9 }10 fmt.Println(string(b))11}12{"Name":"John","Age":24}13import (14type Student struct {15}16func main() {17 s := Student{"John", 24}18 b, err := json.MarshalIndent(s, "", " ")19 if err != nil {20 fmt.Println(err)21 }22 fmt.Println(string(b))23}24{25}26import (27type Student struct {28}29func main() {30 err := json.Unmarshal([]byte(`{"Name":"John","Age":24}`), &s)31 if err != nil {32 fmt.Println(err)33 }34 fmt.Println(s.Name)35}36import (37type Student struct {38}39func main() {40 r := strings.NewReader(`{"Name":"John

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 jsonData := []byte(`{4 }`)5 var data map[string]interface{}6 err := json.Unmarshal(jsonData, &data)7 if err != nil {8 log.Fatal(err)9 }10 fmt.Println(data["first_name"])11 fmt.Println(data["last_name"])12 fmt.Println(data["age"])13}14import (15func main() {16 jsonData := []byte(`{17 }`)18 var data map[string]interface{}19 err := json.Unmarshal(jsonData, &data)20 if err != nil {21 log.Fatal(err)22 }23 fmt.Println(data["first_name"])24 fmt.Println(data["last_name"])25 fmt.Println(data["age"])26}27import (28func main() {29 jsonData := []byte(`{30 }`)31 var data map[string]interface{}32 err := json.Unmarshal(jsonData, &data)33 if err != nil {34 log.Fatal(err)35 }36 fmt.Println(data["first_name"])37 fmt.Println(data["last_name"])38 fmt.Println(data["age"])39}40import (41func main() {

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful