How to use Error method of jsonerror Package

Best Selenoid code snippet using jsonerror.Error

handlers.go

Source:handlers.go Github

copy

Full Screen

...33 }3435 reader, size, err := ws.avatarAssetsHandler.Get(id)36 if err != nil {37 return jsonError(ctx, err, fasthttp.StatusBadRequest)38 }39 defer reader.Close()4041 imgData := make([]byte, size)42 _, err = reader.Read(imgData)43 if err != nil && err != io.EOF {44 return jsonError(ctx, err, fasthttp.StatusInternalServerError)45 }4647 eTag := etag.Generate(imgData, false)4849 ctx.Response.Header.SetContentType("image/png")50 // 24h browser caching51 ctx.Response.Header.Set("Cache-Control", "public, max-age=86400, immutable")52 ctx.Response.Header.Set("ETag", eTag)53 ctx.SetBody(imgData)54 return nil55}5657// -----------------------------------------------------58// --- AUTHORIZATION ---5960// POST /login61func (ws *WebServer) handlerLogin(ctx *routing.Context) error {62 if !ws.auth.Login(ctx) {63 return nil64 }6566 return jsonResponse(ctx, nil, fasthttp.StatusOK)67}6869// GET /accesstoken70func (ws *WebServer) handlerGetAccessToken(ctx *routing.Context) error {71 accessToken, err := ws.auth.ObtainAccessToken(ctx)72 if err != nil {73 return err74 }75 if accessToken == "" {76 return nil77 }7879 return jsonResponse(ctx, &objects.AccessToken{Token: accessToken}, fasthttp.StatusOK)80}8182// GET /refreshtokens83func (ws *WebServer) handlerGetRefreshTokens(ctx *routing.Context) error {84 user := ctx.Get("user").(*objects.User)8586 tokens, err := ws.db.GetRefreshTokens(user.UID)87 if err != nil {88 return jsonError(ctx, err, fasthttp.StatusInternalServerError)89 }9091 for _, t := range tokens {92 t.Sanitize()93 }9495 return jsonResponse(ctx, &listResponse{len(tokens), tokens}, fasthttp.StatusOK)96}9798// DELETE /refreshtokens/:id99func (ws *WebServer) handlerDeleteRefreshToken(ctx *routing.Context) error {100 id := ctx.Param("id")101102 sfId, err := snowflake.ParseString(id)103 if err != nil {104 return jsonError(ctx, err, fasthttp.StatusInternalServerError)105 }106107 err = ws.db.RemoveRefreshToken(sfId)108 if err != nil {109 return jsonError(ctx, err, fasthttp.StatusInternalServerError)110 }111112 return jsonResponse(ctx, nil, fasthttp.StatusOK)113}114115// -----------------------------------------------------116// --- USERS ---117118// POST /users119func (ws *WebServer) handlerCreateUser(ctx *routing.Context) error {120 data := new(loginRequest)121 if err := parseJSONBody(ctx, data); err != nil {122 return jsonError(ctx, err, fasthttp.StatusBadRequest)123 }124125 if ok, err := ws.validateReCaptcha(ctx, &data.reCaptchaResponse); !ok {126 return err127 }128129 if data.UserName == "" || data.Password == "" || len(data.Password) < 8 {130 return jsonError(ctx, errInvalidArguments, fasthttp.StatusBadRequest)131 }132133 user, err := ws.db.GetUser(snowflake.ID(-1), strings.ToLower(data.UserName))134 if err != nil {135 return jsonError(ctx, err, fasthttp.StatusInternalServerError)136 }137 if user != nil {138 return jsonError(ctx, errUNameInUse, fasthttp.StatusConflict)139 }140141 newUser, err := objects.NewUser(data.UserName, data.Password, ws.auth)142 if err != nil {143 return jsonError(ctx, err, fasthttp.StatusInternalServerError)144 }145146 if err = newUser.Validate(false); err != nil {147 return jsonResponse(ctx, err, fasthttp.StatusBadRequest)148 }149150 if err = ws.db.CreateUser(newUser); err != nil {151 return jsonError(ctx, err, fasthttp.StatusInternalServerError)152 }153154 ws.auth.CreateAndSetRefreshToken(ctx, newUser.UID, data.Remember)155156 outUser := *newUser157 outUser.PassHash = nil158159 return jsonResponse(ctx, outUser, fasthttp.StatusCreated)160}161162// GET /users/me163func (ws *WebServer) handlerGetMe(ctx *routing.Context) error {164 user := ctx.Get("user").(*objects.User)165 userOut := *user166 userOut.PassHash = nil167 userOut.HasOldPassword = isOldPasswordHash(user.PassHash)168 return jsonResponse(ctx, userOut, fasthttp.StatusOK)169}170171// POST /users/me172func (ws *WebServer) handlerPostMe(ctx *routing.Context) error {173 user := ctx.Get("user").(*objects.User)174 reqUser := new(userRequest)175 var err error176177 if err = parseJSONBody(ctx, reqUser); err != nil {178 return jsonError(ctx, err, fasthttp.StatusBadRequest)179 }180181 if !ws.auth.CheckHash(string(user.PassHash), reqUser.CurrentPassword) {182 return jsonError(ctx, errUnauthorized, fasthttp.StatusUnauthorized)183 }184185 newUser := &objects.User{186 Username: reqUser.Username,187 DisplayName: reqUser.DisplayName,188 }189190 if err = newUser.Validate(true); err != nil {191 return jsonResponse(ctx, err, fasthttp.StatusBadRequest)192 }193194 if reqUser.NewPassword != "" {195 if len(reqUser.NewPassword) < 8 {196 return jsonError(ctx, fmt.Errorf("invalid new password"), fasthttp.StatusBadRequest)197 }198 var passStr string199 passStr, err = ws.auth.CreateHash(reqUser.NewPassword)200 if err != nil {201 return jsonError(ctx, err, fasthttp.StatusInternalServerError)202 }203 newUser.PassHash = []byte(passStr)204 }205206 user.Update(newUser, false)207208 if err = ws.db.EditUser(user); err != nil {209 return jsonError(ctx, err, fasthttp.StatusInternalServerError)210 }211212 ws.cache.SetUserByID(newUser.UID, user)213214 return jsonResponse(ctx, nil, fasthttp.StatusOK)215}216217// DELETE /users/me218func (ws *WebServer) handlerDeleteMe(ctx *routing.Context) error {219 user := ctx.Get("user").(*objects.User)220 reqUser := new(userRequest)221 var err error222223 if err = parseJSONBody(ctx, reqUser); err != nil {224 return jsonError(ctx, err, fasthttp.StatusBadRequest)225 }226227 if !ws.auth.CheckHash(string(user.PassHash), reqUser.CurrentPassword) {228 return jsonError(ctx, errUnauthorized, fasthttp.StatusUnauthorized)229 }230231 if err = ws.db.DeleteUser(user.UID); err != nil {232 return jsonError(ctx, err, fasthttp.StatusInternalServerError)233 }234235 if err = ws.db.DeleteUserPages(user.UID); err != nil {236 return jsonError(ctx, err, fasthttp.StatusInternalServerError)237 }238239 ws.cache.SetUserByID(user.UID, nil)240241 return ws.auth.Logout(ctx)242}243244// GET /users/:username245func (ws *WebServer) handlerCheckUsername(ctx *routing.Context) error {246 uname := ctx.Param("uname")247248 user, err := ws.db.GetUser(snowflake.ID(-1), strings.ToLower(uname))249 if err != nil {250 return jsonError(ctx, err, fasthttp.StatusInternalServerError)251 }252253 status := fasthttp.StatusOK254 if user == nil {255 status = fasthttp.StatusNotFound256 }257258 return jsonResponse(ctx, nil, status)259}260261// POST /users/me/pageorder262func (ws *WebServer) handlerPostPageOrder(ctx *routing.Context) error {263 user := ctx.Get("user").(*objects.User)264265 queryArgs := ctx.QueryArgs()266 champion := string(queryArgs.Peek("champion"))267268 if champion == "" {269 champion = "general"270 }271272 pageOrder := new(pageOrderRequest)273 if err := parseJSONBody(ctx, pageOrder); err != nil {274 return jsonError(ctx, err, fasthttp.StatusBadRequest)275 }276277 if user.PageOrder == nil {278 user.PageOrder = make(map[string][]snowflake.ID)279 }280281 user.PageOrder[champion] = pageOrder.PageOrder282 if err := ws.db.EditUser(user); err != nil {283 return jsonError(ctx, err, fasthttp.StatusInternalServerError)284 }285286 return jsonResponse(ctx, nil, fasthttp.StatusOK)287}288289// POST /users/me/mail290func (ws *WebServer) handlerPostMail(ctx *routing.Context) error {291 if ws.ms == nil {292 return jsonError(ctx, errors.New("mail server disabled by config"), fasthttp.StatusServiceUnavailable)293 }294295 user := ctx.Get("user").(*objects.User)296297 mail := new(setMailRequest)298 if err := parseJSONBody(ctx, mail); err != nil {299 return jsonError(ctx, err, fasthttp.StatusBadRequest)300 }301302 if !ws.auth.CheckHash(string(user.PassHash), mail.CurrentPassword) {303 return jsonError(ctx, errUnauthorized, fasthttp.StatusUnauthorized)304 }305306 if mail.Reset {307 user.MailAddress = ""308 if err := ws.db.EditUser(user); err != nil {309 return jsonError(ctx, err, fasthttp.StatusInternalServerError)310 }311312 ws.cache.SetUserByID(user.UID, user)313314 return jsonResponse(ctx, nil, fasthttp.StatusOK)315 }316317 recUser, err := ws.db.GetUser(-1, mail.MailAddress)318 if err != nil {319 return jsonError(ctx, err, fasthttp.StatusInternalServerError)320 }321 if recUser != nil && recUser.UID != user.UID {322 return jsonError(ctx, errEmailAlreadyTaken, fasthttp.StatusBadRequest)323 }324325 const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"326 token, err := random.String(16, charset)327 if err != nil {328 return jsonError(ctx, err, fasthttp.StatusInternalServerError)329 }330331 mailText := fmt.Sprintf(332 "Please open the following link to confirm your E-Mail address:\n"+333 "%s/mailConfirmation?token=%s", ws.config.PublicAddr, token)334335 err = ws.ms.SendMailFromDef(mail.MailAddress, "E-Mail confirmation | myrunes", mailText, "text/plain")336 if err != nil {337 return jsonError(ctx, err, fasthttp.StatusBadRequest)338 }339340 ws.mailConfirmation.Set(token, &mailConfirmationData{341 MailAddress: mail.MailAddress,342 UserID: user.UID,343 }, 12*time.Hour)344345 return jsonResponse(ctx, nil, fasthttp.StatusOK)346}347348// POST /users/me/mail/confirm349func (ws *WebServer) handlerPostConfirmMail(ctx *routing.Context) error {350 token := new(confirmMail)351 if err := parseJSONBody(ctx, token); err != nil {352 return jsonError(ctx, err, fasthttp.StatusBadRequest)353 }354355 if !ws.mailConfirmation.Contains(token.Token) {356 return jsonError(ctx, fmt.Errorf("invalid token"), fasthttp.StatusBadRequest)357 }358359 data, ok := ws.mailConfirmation.GetValue(token.Token).(*mailConfirmationData)360 if !ok {361 return jsonError(ctx, fmt.Errorf("wrong data struct in timedmap"), fasthttp.StatusInternalServerError)362 }363364 ws.mailConfirmation.Remove(token.Token)365366 if user, err := ws.cache.GetUserByID(data.UserID); err == nil && user != nil {367 user.MailAddress = data.MailAddress368 if err := ws.db.EditUser(user); err != nil {369 return jsonError(ctx, err, fasthttp.StatusInternalServerError)370 }371 ws.cache.SetUserByID(user.UID, user)372 }373374 return jsonResponse(ctx, nil, fasthttp.StatusOK)375}376377// POST /users/me/passwordreset378func (ws *WebServer) handlerPostPwReset(ctx *routing.Context) error {379 if ws.ms == nil {380 return jsonError(ctx, errors.New("mail server disabled by config"), fasthttp.StatusServiceUnavailable)381 }382383 reset := new(passwordReset)384 if err := parseJSONBody(ctx, reset); err != nil {385 return jsonError(ctx, err, fasthttp.StatusBadRequest)386 }387388 user, err := ws.db.GetUser(-1, reset.MailAddress)389 if err != nil {390 return jsonError(ctx, err, fasthttp.StatusInternalServerError)391 }392393 if user == nil || user.MailAddress == "" {394 return jsonResponse(ctx, nil, fasthttp.StatusOK)395 }396397 const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"398 token, err := random.String(24, charset)399 if err != nil {400 return jsonError(ctx, err, fasthttp.StatusInternalServerError)401 }402403 mailText := fmt.Sprintf("Please follow the link below to reset your accounts password:\n"+404 "%s/passwordReset?token=%s", ws.config.PublicAddr, token)405 err = ws.ms.SendMailFromDef(user.MailAddress, "Password reset | myrunes", mailText, "text/plain")406 if err == nil {407 ws.pwReset.Set(token, user.UID, 10*time.Minute)408 }409410 return jsonResponse(ctx, nil, fasthttp.StatusOK)411}412413// POST /users/me/passwordreset/confirm414func (ws *WebServer) handlerPostPwResetConfirm(ctx *routing.Context) error {415 data := new(confirmPasswordReset)416 if err := parseJSONBody(ctx, data); err != nil {417 return jsonError(ctx, err, fasthttp.StatusBadRequest)418 }419420 if data.NewPassword == "" || len(data.NewPassword) < 8 {421 return jsonError(ctx, fmt.Errorf("invalid password length"), fasthttp.StatusBadRequest)422 }423424 if !ws.pwReset.Contains(data.Token) {425 return jsonError(ctx, fmt.Errorf("invalid token"), fasthttp.StatusBadRequest)426 }427428 if ok, err := ws.validateReCaptcha(ctx, &data.reCaptchaResponse); !ok {429 return err430 }431432 uID, ok := ws.pwReset.GetValue(data.Token).(snowflake.ID)433 if !ok {434 return jsonError(ctx, fmt.Errorf("wrong data struct in timedmap"), fasthttp.StatusInternalServerError)435 }436437 user, err := ws.db.GetUser(uID, "")438 if err != nil {439 return jsonError(ctx, err, fasthttp.StatusInternalServerError)440 }441442 if user == nil {443 return jsonError(ctx, fmt.Errorf("unknown user"), fasthttp.StatusBadRequest)444 }445446 ws.pwReset.Remove(data.Token)447448 var passStr string449 passStr, err = ws.auth.CreateHash(data.NewPassword)450 if err != nil {451 return jsonError(ctx, err, fasthttp.StatusInternalServerError)452 }453 user.PassHash = []byte(passStr)454455 if err = ws.db.EditUser(user); err != nil {456 return jsonError(ctx, err, fasthttp.StatusInternalServerError)457 }458459 return jsonResponse(ctx, nil, fasthttp.StatusOK)460}461462// -----------------------------------------------------463// --- PAGES ---464465// POST /pages466func (ws *WebServer) handlerCreatePage(ctx *routing.Context) error {467 var err error468 page := objects.NewEmptyPage()469470 if err = parseJSONBody(ctx, page); err != nil {471 return jsonError(ctx, err, fasthttp.StatusBadRequest)472 }473474 if err = page.Validate(); err != nil {475 return jsonError(ctx, err, fasthttp.StatusBadRequest)476 }477478 user := ctx.Get("user").(*objects.User)479 page.FinalizeCreate(user.UID)480481 if err = ws.db.CreatePage(page); err != nil {482 return jsonError(ctx, err, fasthttp.StatusInternalServerError)483 }484 ws.cache.SetPageByID(page.UID, page)485486 return jsonResponse(ctx, page, fasthttp.StatusCreated)487}488489// GET /pages490func (ws *WebServer) handlerGetPages(ctx *routing.Context) error {491 user := ctx.Get("user").(*objects.User)492 queryArgs := ctx.QueryArgs()493494 sortBy := string(queryArgs.Peek("sortBy"))495 filter := string(queryArgs.Peek("filter"))496 champion := string(queryArgs.Peek("champion"))497 short := string(queryArgs.Peek("short"))498499 if champion == "" {500 champion = "general"501 }502503 var sortFunc func(i, j *objects.Page) bool504505 switch sortBy {506 case "created":507 sortFunc = func(i, j *objects.Page) bool {508 return i.Created.After(j.Created)509 }510 case "title":511 sortFunc = func(i, j *objects.Page) bool {512 return comparison.Alphabetically(i.Title, j.Title)513 }514 case "custom":515 if user.PageOrder != nil {516 pageOrder, ok := user.PageOrder[champion]517 if ok {518 sortFunc = func(i, j *objects.Page) bool {519 var pix, jix int520 for ix, uid := range pageOrder {521 if uid == i.UID {522 pix = ix523 } else if uid == j.UID {524 jix = ix525 }526 }527 return jix > pix528 }529 }530 }531 }532533 pages, err := ws.db.GetPages(user.UID, champion, filter, sortFunc)534 if err != nil {535 return jsonError(ctx, err, fasthttp.StatusInternalServerError)536 }537538 if comparison.IsTrue(short) {539 m := make(map[string]int)540 for _, p := range pages {541 for _, c := range p.Champions {542 if _, ok := m[c]; !ok {543 m[c] = 1544 } else {545 m[c]++546 }547 }548 }549550 return jsonResponse(ctx, &listResponse{N: len(m), Data: m}, fasthttp.StatusOK)551 }552553 return jsonResponse(ctx, &listResponse{N: len(pages), Data: pages}, fasthttp.StatusOK)554}555556// GET /pages/:id557func (ws *WebServer) handlerGetPage(ctx *routing.Context) error {558 user := ctx.Get("user").(*objects.User)559 _uid := ctx.Param("uid")560 uid, err := snowflake.ParseString(_uid)561 if err != nil {562 return jsonError(ctx, err, fasthttp.StatusBadRequest)563 }564565 page, err := ws.cache.GetPageByID(uid)566 if err != nil {567 return jsonError(ctx, err, fasthttp.StatusInternalServerError)568 }569570 if page == nil || page.Owner != user.UID {571 return jsonError(ctx, errNotFound, fasthttp.StatusNotFound)572 }573574 return jsonResponse(ctx, page, fasthttp.StatusOK)575}576577// POST /pages/:id578func (ws *WebServer) handlerEditPage(ctx *routing.Context) error {579 user := ctx.Get("user").(*objects.User)580 _uid := ctx.Param("uid")581 uid, err := snowflake.ParseString(_uid)582 if err != nil {583 return jsonError(ctx, err, fasthttp.StatusBadRequest)584 }585586 page, err := ws.cache.GetPageByID(uid)587 if err != nil {588 return jsonError(ctx, err, fasthttp.StatusInternalServerError)589 }590591 if page == nil || page.Owner != user.UID {592 return jsonError(ctx, errNotFound, fasthttp.StatusNotFound)593 }594595 newPage := new(objects.Page)596 if err = parseJSONBody(ctx, newPage); err != nil {597 return jsonError(ctx, err, fasthttp.StatusBadRequest)598 }599600 page.Update(newPage)601 if err = page.Validate(); err != nil {602 return jsonError(ctx, err, fasthttp.StatusBadRequest)603 }604605 if err = ws.db.EditPage(page); err != nil {606 return jsonError(ctx, err, fasthttp.StatusInternalServerError)607 }608 ws.cache.SetPageByID(page.UID, page)609610 return jsonResponse(ctx, newPage, fasthttp.StatusOK)611}612613// DELETE /pages/:id614func (ws *WebServer) handlerDeletePage(ctx *routing.Context) error {615 user := ctx.Get("user").(*objects.User)616 _uid := ctx.Param("uid")617 uid, err := snowflake.ParseString(_uid)618 if err != nil {619 return jsonError(ctx, err, fasthttp.StatusBadRequest)620 }621622 page, err := ws.cache.GetPageByID(uid)623 if err != nil {624 return jsonError(ctx, err, fasthttp.StatusInternalServerError)625 }626627 if page == nil || page.Owner != user.UID {628 return jsonError(ctx, errNotFound, fasthttp.StatusNotFound)629 }630631 if err = ws.db.DeletePage(page.UID); err != nil {632 return jsonError(ctx, err, fasthttp.StatusInternalServerError)633 }634 ws.cache.SetPageByID(page.UID, nil)635636 return jsonResponse(ctx, nil, fasthttp.StatusOK)637}638639// -----------------------------------------------------640// --- RESOURCES & STATICS ---641642// GET /resources/champions643func (ws *WebServer) handlerGetChamps(ctx *routing.Context) error {644 return jsonCachableResponse(ctx, &listResponse{N: len(ddragon.DDragonInstance.Champions), Data: ddragon.DDragonInstance.Champions}, fasthttp.StatusOK)645}646647// GET /resources/runes648func (ws *WebServer) handlerGetRunes(ctx *routing.Context) error {649 data := map[string]interface{}{650 "trees": ddragon.DDragonInstance.Runes,651 "perks": objects.PerksPool,652 }653 return jsonCachableResponse(ctx, data, fasthttp.StatusOK)654}655656// GET /version657func (ws *WebServer) handlerGetVersion(ctx *routing.Context) error {658 return jsonCachableResponse(ctx, map[string]string{659 "version": static.AppVersion,660 "apiversion": static.APIVersion,661 "release": static.Release,662 }, fasthttp.StatusOK)663}664665// GET /recaptchainfo666func (ws *WebServer) handlerGetReCaptchaInfo(ctx *routing.Context) error {667 if ws.config.ReCaptcha == nil || ws.config.ReCaptcha.SiteKey == "" {668 return jsonError(ctx, errors.New("not configured"), fasthttp.StatusBadRequest)669 }670671 return jsonCachableResponse(ctx, map[string]string{672 "sitekey": ws.config.ReCaptcha.SiteKey,673 }, fasthttp.StatusOK)674}675676// -----------------------------------------------------677// --- FAVORITES ---678679// POST /favorites680func (ws *WebServer) handlerPostFavorite(ctx *routing.Context) error {681 user := ctx.Get("user").(*objects.User)682 var err error683684 favReq := new(alterFavoriteRequest)685 if err = parseJSONBody(ctx, favReq); err != nil {686 return jsonError(ctx, err, fasthttp.StatusBadRequest)687 }688689 if favReq.Favorites == nil {690 return jsonError(ctx, errBadRequest, fasthttp.StatusBadRequest)691 }692693 champMap := make(map[string]interface{})694 for _, c := range ddragon.DDragonInstance.Champions {695 champMap[c.UID] = nil696 }697698 for i, f := range favReq.Favorites {699 favReq.Favorites[i] = strings.ToLower(f)700 if _, ok := champMap[f]; !ok {701 return jsonError(ctx, objects.ErrInvalidChamp, fasthttp.StatusBadRequest)702 }703 }704705 user.Favorites = favReq.Favorites706707 if err = ws.db.EditUser(user); err != nil {708 return jsonError(ctx, err, fasthttp.StatusInternalServerError)709 }710711 return jsonResponse(ctx,712 listResponse{N: len(user.Favorites), Data: user.Favorites},713 fasthttp.StatusOK)714}715716// GET /favorites717func (ws *WebServer) handlerGetFavorites(ctx *routing.Context) error {718 user := ctx.Get("user").(*objects.User)719720 if user.Favorites == nil {721 user.Favorites = []string{}722 }723724 return jsonResponse(ctx,725 listResponse{N: len(user.Favorites), Data: user.Favorites},726 fasthttp.StatusOK)727}728729// -----------------------------------------------------730// --- SHARES ---731732// POST /shares733func (ws *WebServer) handlerCreateShare(ctx *routing.Context) error {734 user := ctx.Get("user").(*objects.User)735 var err error736737 params := new(createShareRequest)738 if err := parseJSONBody(ctx, params); err != nil {739 return jsonError(ctx, err, fasthttp.StatusBadRequest)740 }741742 pageID, err := snowflake.ParseString(params.Page)743 if err != nil {744 return jsonError(ctx, err, fasthttp.StatusBadRequest)745 }746747 if page, err := ws.cache.GetPageByID(pageID); err != nil {748 return jsonResponse(ctx, err, fasthttp.StatusInternalServerError)749 } else if page == nil || page.Owner != user.UID {750 return jsonError(ctx, errNotFound, fasthttp.StatusNotFound)751 }752753 share, err := objects.NewSharePage(user.UID, pageID, params.MaxAccesses, params.Expires)754 if err != nil {755 return jsonError(ctx, err, fasthttp.StatusInternalServerError)756 }757758 if err = ws.db.SetShare(share); err != nil {759 return jsonError(ctx, err, fasthttp.StatusInternalServerError)760 }761762 return jsonResponse(ctx, share, fasthttp.StatusCreated)763}764765// POST /shares/:id766func (ws *WebServer) handlerPostShare(ctx *routing.Context) error {767 user := ctx.Get("user").(*objects.User)768769 _uid := ctx.Param("uid")770 uid, err := snowflake.ParseString(_uid)771 if err != nil {772 return jsonError(ctx, err, fasthttp.StatusBadRequest)773 }774775 share, err := ws.db.GetShare("", uid, -1)776 if err != nil {777 return jsonResponse(ctx, err, fasthttp.StatusInternalServerError)778 }779 if share == nil {780 return jsonError(ctx, errNotFound, fasthttp.StatusNotFound)781 }782783 if share.OwnerID != user.UID {784 return jsonError(ctx, errNotFound, fasthttp.StatusNotFound)785 }786787 params := new(createShareRequest)788 if err := parseJSONBody(ctx, params); err != nil {789 return jsonError(ctx, errBadRequest, fasthttp.StatusBadRequest)790 }791792 if (params.Expires != time.Time{}) {793 share.Expires = params.Expires794 }795796 if params.MaxAccesses != 0 {797 share.MaxAccesses = params.MaxAccesses798 }799800 if err = ws.db.SetShare(share); err != nil {801 return jsonError(ctx, err, fasthttp.StatusInternalServerError)802 }803804 return jsonResponse(ctx, share, fasthttp.StatusCreated)805}806807// GET /shares/:id808func (ws *WebServer) handlerGetShare(ctx *routing.Context) error {809 ident := ctx.Param("ident")810 byIdent := true811 var user *objects.User812813 _user := ctx.Get("user")814 if _user != nil {815 user = _user.(*objects.User)816 byIdent = false817 }818819 shareID, err := snowflake.ParseString(ident)820 if err != nil || user == nil {821 shareID = -1822 }823824 share, err := ws.db.GetShare(ident, shareID, shareID)825 if err != nil {826 return jsonError(ctx, err, fasthttp.StatusInternalServerError)827 }828 if share == nil || (user != nil && share.OwnerID != user.UID) {829 return jsonError(ctx, errNotFound, fasthttp.StatusNotFound)830 }831832 if byIdent && (share.MaxAccesses == 0 || (share.Expires != time.Time{} && share.Expires.Before(time.Now()))) {833 return jsonError(ctx, errNotFound, fasthttp.StatusNotFound)834 }835836 page, err := ws.cache.GetPageByID(share.PageID)837 if err != nil {838 return jsonError(ctx, err, fasthttp.StatusInternalServerError)839 }840 if page == nil {841 return jsonError(ctx, errNotFound, fasthttp.StatusNotFound)842 }843844 owner, err := ws.cache.GetUserByID(page.Owner)845 if err != nil {846 return jsonError(ctx, err, fasthttp.StatusInternalServerError)847 }848849 reqAddr := shared.GetIPAddr(ctx)850 validReqAddr := !strings.HasPrefix(reqAddr, "192.168") &&851 !strings.HasPrefix(reqAddr, "10.23") &&852 !(static.Release == "TRUE" && reqAddr == "127.0.0.1") &&853 string(ctx.Request.Header.PeekBytes(headerUserAgent)) != static.DiscordUserAgentPingHeaderVal854855 if byIdent && validReqAddr {856 var contains bool857 for _, ip := range share.AccessIPs {858 if ip == reqAddr {859 contains = true860 }861 }862863 if !contains {864 share.AccessIPs = append(share.AccessIPs, reqAddr)865866 if share.MaxAccesses > 0 {867 share.MaxAccesses--868 }869870 share.LastAccess = time.Now()871 share.Accesses++872873 if err = ws.db.SetShare(share); err != nil {874 return jsonError(ctx, err, fasthttp.StatusInternalServerError)875 }876 }877 }878879 share.AccessIPs = nil880881 return jsonResponse(ctx, &shareResponse{882 Page: page,883 Share: share,884 User: owner.Sanitize(),885 }, fasthttp.StatusAccepted)886}887888// DELETE /shares/:id889func (ws *WebServer) handlerDeleteShare(ctx *routing.Context) error {890 user := ctx.Get("user").(*objects.User)891892 _uid := ctx.Param("uid")893 uid, err := snowflake.ParseString(_uid)894 if err != nil {895 return jsonError(ctx, err, fasthttp.StatusBadRequest)896 }897898 share, err := ws.db.GetShare("", uid, -1)899 if err != nil {900 return jsonError(ctx, err, fasthttp.StatusInternalServerError)901 }902 if share == nil || share.OwnerID != user.UID {903 return jsonError(ctx, errNotFound, fasthttp.StatusNotFound)904 }905906 if err = ws.db.DeleteShare("", uid, -1); err != nil {907 return jsonError(ctx, err, fasthttp.StatusInternalServerError)908 }909910 return jsonResponse(ctx, nil, fasthttp.StatusOK)911}912913// -----------------------------------------------------914// --- API TOKEN ---915916// POST /apitoken917func (ws *WebServer) handlerPostAPIToken(ctx *routing.Context) error {918 user := ctx.Get("user").(*objects.User)919 var err error920 token := new(objects.APIToken)921922 if token.Token, err = random.Base64(apiTokenLength); err != nil {923 return jsonError(ctx, err, fasthttp.StatusInternalServerError)924 }925926 token.UserID = user.UID927 token.Created = time.Now()928929 if err = ws.db.SetAPIToken(token); err != nil {930 return jsonError(ctx, err, fasthttp.StatusInternalServerError)931 }932 ws.cache.SetUserByToken(token.Token, user)933934 return jsonResponse(ctx, token, fasthttp.StatusOK)935}936937// GET /apitoken938func (ws *WebServer) handlerGetAPIToken(ctx *routing.Context) error {939 user := ctx.Get("user").(*objects.User)940941 token, err := ws.db.GetAPIToken(user.UID)942 if err != nil {943 return jsonError(ctx, err, fasthttp.StatusInternalServerError)944 }945946 if token == nil {947 return jsonError(ctx, errNotFound, fasthttp.StatusNotFound)948 }949950 return jsonResponse(ctx, token, fasthttp.StatusOK)951}952953// DELETE /apitoken954func (ws *WebServer) handlerDeleteAPIToken(ctx *routing.Context) error {955 user := ctx.Get("user").(*objects.User)956957 token, err := ws.db.GetAPIToken(user.UID)958 if err != nil {959 return jsonError(ctx, err, fasthttp.StatusInternalServerError)960 }961962 if token != nil {963 ws.cache.SetUserByToken(token.Token, nil)964 }965966 if err := ws.db.ResetAPIToken(user.UID); err != nil {967 return jsonError(ctx, err, fasthttp.StatusInternalServerError)968 }969970 return jsonResponse(ctx, nil, fasthttp.StatusOK)971} ...

Full Screen

Full Screen

tunnel.go

Source:tunnel.go Github

copy

Full Screen

...32 clientLocalPort := request.PostFormValue("client_local_port")33 clientLocalHost := request.PostFormValue("client_local_host")34 fmt.Printf("cluster add processing 000\n")35 if mode == "" {36 jsonError(responseWrite, "必须选择一种模式!", nil)37 return38 }39 if(mode != "0" && mode != "1" && mode != "2") {40 jsonError(responseWrite, "模式选择错误!", nil)41 return42 }43 if name == "" {44 jsonError(responseWrite, "隧道名称不能为空!", nil)45 return46 }47 if userId == "" {48 jsonError(responseWrite, "user_id 不能为空!", nil)49 return50 }51 if clusterId == "" {52 jsonError(responseWrite, "没有选择节点!", nil)53 return54 }55 if serverId == "" {56 jsonError(responseWrite, "没有选择server!", nil)57 return58 }59 if clientId == "" {60 jsonError(responseWrite, "没有选择client!", nil)61 return62 }63 if protocol == "" {64 jsonError(responseWrite, "没有选择协议!", nil)65 return66 }67 if serverListenPort == "" {68 jsonError(responseWrite, "server监听端口不能为空!", nil)69 return70 }71 if serverListenIp == "" {72 jsonError(responseWrite, "server绑定Ip不能为空!", nil)73 return74 }75 if clientLocalPort == "" {76 jsonError(responseWrite, "client监听端口不能为空!", nil)77 return78 }79 if clientLocalHost == "" {80 jsonError(responseWrite, "client绑定Ip不能为空!", nil)81 return82 }83 db := G.DB()84 var rs *mysql.ResultSet85 //cluster存在86 rs, err := db.Query(db.AR().From("cluster").Where(map[string]interface{}{87 "cluster_id": clusterId,88 "is_delete": 0,89 }).Limit(0, 1))90 if err != nil {91 jsonError(responseWrite, err.Error(), nil)92 return93 }94 if(rs.Len() == 0) {95 jsonError(responseWrite, "cluster不存在!", nil)96 }97 fmt.Printf("cluster rs.len : %d mode: %d\n",rs.Len(),mode)98 //基础模式99 // 1.server 必须为系统server100 // 2.server 必须在所选的cluster在线101 // 3.client 存在102 if(mode == "0") {103 //必须为系统server104 rs, err := db.Query(db.AR().From("server").Where(map[string]interface{}{105 "server_id": serverId,106 "user_id": 0,107 "is_delete": 0,108 }).Limit(0, 1))109 if err != nil {110 jsonError(responseWrite, err.Error(), nil)111 return112 }113 if(rs.Len() == 0) {114 jsonError(responseWrite, "基础模式下必须为系统server", nil)115 }116 //在cluster上且在线117 rs, err = db.Query(db.AR().From("online").Where(map[string]interface{}{118 "cs_id": serverId,119 "cs_type": "server",120 "cluster_id": clusterId,121 }).Limit(0, 1))122 if err != nil {123 jsonError(responseWrite, err.Error(), nil)124 return125 }126 if(rs.Len() == 0) {127 jsonError(responseWrite, "基础模式下server必须在线", nil)128 }129 //client存在130 rs, err = db.Query(db.AR().From("client").Where(map[string]interface{}{131 "client_id": clientId,132 "user_id": userId,133 "is_delete": 0,134 }).Limit(0, 1))135 if err != nil {136 jsonError(responseWrite, err.Error(), nil)137 return138 }139 if(rs.Len() == 0) {140 jsonError(responseWrite, "client不存在", nil)141 }142 }143 //高级模式144 // 1.client存在145 // 2.server存在146 if(mode == "1") {147 //server存在148 rs, err := db.Query(db.AR().From("server").Where(map[string]interface{}{149 "server_id": serverId,150 "user_id": userId,151 "is_delete": 0,152 }).Limit(0, 1))153 if err != nil {154 jsonError(responseWrite, err.Error(), nil)155 return156 }157 if(rs.Len() == 0) {158 jsonError(responseWrite, "server不存在!", nil)159 }160 //client存在161 rs, err = db.Query(db.AR().From("client").Where(map[string]interface{}{162 "client_id": clientId,163 "user_id": userId,164 "is_delete": 0,165 }).Limit(0, 1))166 if err != nil {167 jsonError(responseWrite, err.Error(), nil)168 return169 }170 if(rs.Len() == 0) {171 jsonError(responseWrite, "client不存在", nil)172 }173 }174 //特殊模式175 // 1.client 必须为系统server176 // 2.client 必须在所选的cluster在线177 // 3.server 存在178 if(mode == "2") {179 //必须为系统client180 rs, err := db.Query(db.AR().From("server").Where(map[string]interface{}{181 "client_id": clientId,182 "user_id": 0,183 "is_delete": 0,184 }).Limit(0, 1))185 if err != nil {186 jsonError(responseWrite, err.Error(), nil)187 return188 }189 if(rs.Len() == 0) {190 jsonError(responseWrite, "特殊模式下必须为系统client", nil)191 }192 //在cluster上且在线193 rs, err = db.Query(db.AR().From("online").Where(map[string]interface{}{194 "cs_id": clientId,195 "cs_type": "client",196 "cluster_id": clusterId,197 }).Limit(0, 1))198 if err != nil {199 jsonError(responseWrite, err.Error(), nil)200 return201 }202 if(rs.Len() == 0) {203 jsonError(responseWrite, "特殊模式下client必须在线", nil)204 }205 //server存在206 rs, err = db.Query(db.AR().From("server").Where(map[string]interface{}{207 "server_id": clientId,208 "user_id": userId,209 "is_delete": 0,210 }).Limit(0, 1))211 if err != nil {212 jsonError(responseWrite, err.Error(), nil)213 return214 }215 if(rs.Len() == 0) {216 jsonError(responseWrite, "server不存在", nil)217 }218 }219 //server_ip 和 cluster_id220 //add tunnel221 tunnelValues := map[string]interface{}{222 "mode": mode,223 "name": name,224 "user_id": userId,225 "cluster_id": clusterId,226 "server_id": serverId,227 "client_id": clientId,228 "protocol": protocol,229 "status": 1,230 "is_open": 1,231 "server_listen_port": serverListenPort,232 "server_listen_ip": serverListenIp,233 "client_local_port": clientLocalPort,234 "client_local_host": clientLocalHost,235 "create_time": time.Now().Unix(),236 "update_time": time.Now().Unix(),237 }238 rs, err = db.Exec(db.AR().Insert("tunnel", tunnelValues))239 if err != nil {240 jsonError(responseWrite, err.Error(), nil)241 return242 }243 id := rs.LastInsertId244 jsonSuccess(responseWrite, "添加隧道成功", id)245}246//update by tunnel247//method : POST248//params : mode, name, user_id, cluster_id, server_id,client_id, protocol,249// server_listen_port, server_listen_ip, client_local_port,client_local_host250func (tunnel *Tunnel) Update(responseWrite http.ResponseWriter, request *http.Request, params httprouter.Params) {251 tunnelId := request.PostFormValue("tunnel_id")252 mode := request.PostFormValue("mode")253 name := request.PostFormValue("name")254 userId := request.PostFormValue("user_id")255 clusterId := request.PostFormValue("cluster_id")256 serverId := request.PostFormValue("server_id")257 clientId := request.PostFormValue("client_id")258 protocol := request.PostFormValue("protocol")259 serverListenPort := request.PostFormValue("server_listen_port")260 serverListenIp := request.PostFormValue("server_listen_ip")261 clientLocalPort := request.PostFormValue("client_local_port")262 clientLocalHost := request.PostFormValue("client_local_host")263 if tunnelId == "" {264 jsonError(responseWrite, "tunnel_id is not empty!", nil)265 return266 }267 if mode == "" {268 jsonError(responseWrite, "mode is not empty!", nil)269 return270 }271 if(mode != "1" && mode != "0") {272 jsonError(responseWrite, "mode is error!", nil)273 return274 }275 if name == "" {276 jsonError(responseWrite, "name is not empty!", nil)277 return278 }279 if userId == "" {280 jsonError(responseWrite, "user_id is not empty!", nil)281 return282 }283 if clusterId == "" {284 jsonError(responseWrite, "cluster_id is not empty!", nil)285 return286 }287 if serverId == "" {288 jsonError(responseWrite, "server_id is not empty!", nil)289 return290 }291 if clientId == "" {292 jsonError(responseWrite, "client_id is not empty!", nil)293 return294 }295 if protocol == "" {296 jsonError(responseWrite, "protocol is not empty!", nil)297 return298 }299 if serverListenPort == "" {300 jsonError(responseWrite, "server_listen_port is not empty!", nil)301 return302 }303 if serverListenIp == "" {304 jsonError(responseWrite, "server_listen_ip is not empty!", nil)305 return306 }307 if clientLocalPort == "" {308 jsonError(responseWrite, "client_local_port is not empty!", nil)309 return310 }311 if clientLocalHost == "" {312 jsonError(responseWrite, "client_local_host is not empty!", nil)313 return314 }315 db := G.DB()316 var rs *mysql.ResultSet317 rs, err := db.Query(db.AR().From("tunnel").Where(map[string]interface{}{318 "tunnel_id": tunnelId,319 "is_delete": 0,320 }).Limit(0, 1))321 if err != nil {322 jsonError(responseWrite, err.Error(), nil)323 return324 }325 if rs.Len() == 0 {326 jsonError(responseWrite, "tunnel is not exist", nil)327 return328 }329 //tunnel values330 tunnelValues := map[string]interface{}{331 "mode": mode,332 "name": name,333 "user_id": userId,334 "cluster_id": clusterId,335 "server_id": serverId,336 "client_id": clientId,337 "protocol": protocol,338 "server_listen_port": serverListenPort,339 "server_listen_ip": serverListenIp,340 "client_local_port": clientLocalPort,341 "client_localhost": clientLocalHost,342 "update_time": time.Now().Unix(),343 }344 rs, err = db.Exec(db.AR().Update("tunnel", tunnelValues, map[string]interface{}{345 "tunnel_id": tunnelId,346 }))347 if err != nil {348 jsonError(responseWrite, err.Error(), nil)349 return350 }351 id := rs.LastInsertId352 jsonSuccess(responseWrite, "update tunnel success", id)353}354//delete a tunnel by tunnel_id355//method : GET356//params : tunnel_id357func (tunnel *Tunnel) Delete(responseWrite http.ResponseWriter, request *http.Request, params httprouter.Params) {358 tunnelId := request.FormValue("tunnel_id")359 if tunnelId == "" {360 jsonError(responseWrite, "tunnel_id error!", nil)361 return362 }363 db := G.DB()364 var rs *mysql.ResultSet365 rs, err := db.Query(db.AR().From("tunnel").Where(map[string]interface{}{366 "tunnel_id": tunnelId,367 "is_delete": 0,368 }).Limit(0, 1))369 if err != nil {370 jsonError(responseWrite, err.Error(), nil)371 return372 }373 if rs.Len() == 0 {374 jsonError(responseWrite, "隧道不存在", nil)375 return376 }377 //判断是否打开378 tunnelRow := rs.Row()379 if(tunnelRow["is_open"] == "1") {380 jsonError(responseWrite, "请先关闭隧道再删除", nil)381 return382 }383 tunnelValues := map[string]interface{}{384 "is_delete": 1,385 "update_time": time.Now().Unix(),386 }387 rs, err = db.Exec(db.AR().Update("tunnel", tunnelValues, map[string]interface{}{388 "tunnel_id": tunnelId,389 }))390 if err != nil {391 jsonError(responseWrite, err.Error(), nil)392 return393 }394 jsonSuccess(responseWrite, "delete tunnel success", nil)395}396//tunnel list397//method : GET398//params: keyword("") page(1) number(15) user_id399func (tunnel *Tunnel) List(responseWrite http.ResponseWriter, request *http.Request, params httprouter.Params) {400 keyword := strings.Trim(request.FormValue("keyword"), "")401 page := request.FormValue("page")402 pageSize := request.FormValue("number")403 userId := request.FormValue("user_id")404 pageNumber := 1405 number := 15406 if page != "" {407 pageNumber, _ = strconv.Atoi(page)408 }409 if pageSize != "" {410 number, _ = strconv.Atoi(pageSize)411 }412 offset := (pageNumber - 1) * number413 db := G.DB()414 var rs *mysql.ResultSet415 var err error416 tunnelRows := []map[string]string{}417 if keyword != "" {418 sqlString := "SELECT * FROM at_tunnel where is_delete=0"419 if userId != "" {420 sqlString += " AND user_id=" + userId421 }422 sqlString += " AND (" +423 "server_local_ip='" + keyword + "' OR " +424 "client_local_host='" + keyword + "'" +425 ")"426 sql := db.AR().Raw(sqlString)427 rs, err = db.Query(sql)428 if err != nil {429 jsonError(responseWrite, err.Error(), nil)430 return431 }432 tunnelRows = rs.Rows()433 } else {434 sql := db.AR().From("tunnel")435 if userId != "" {436 sql = sql.Where(map[string]interface{}{"is_delete": 0, "user_id": userId})437 } else {438 sql = sql.Where(map[string]interface{}{"is_delete": 0})439 }440 sql = sql.Limit(offset, number)441 rs, err = db.Query(sql)442 if err != nil {443 jsonError(responseWrite, err.Error(), nil)444 return445 }446 tunnelRows = rs.Rows()447 }448 jsonSuccess(responseWrite, "ok", tunnelRows)449}450//get tunnel by tunnel_id451//method : GET452//params : tunnel_id453func (tunnel *Tunnel) GetTunnelByTunnelId(responseWrite http.ResponseWriter, request *http.Request, params httprouter.Params) {454 tunnelId := request.FormValue("tunnel_id")455 if tunnelId == "" {456 jsonError(responseWrite, "tunnel_id is error!", nil)457 return458 }459 db := G.DB()460 var rs *mysql.ResultSet461 rs, err := db.Query(db.AR().From("tunnel").Where(map[string]interface{}{462 "tunnel_id": tunnelId,463 "is_delete": 0,464 }).Limit(0, 1))465 if err != nil {466 jsonError(responseWrite, err.Error(), nil)467 return468 }469 if rs.Len() == 0 {470 jsonError(responseWrite, "tunnel is not exists", nil)471 return472 }473 jsonSuccess(responseWrite, "ok", rs.Row())474}475//get tunnel by client_id476//method : GET477//params : client_id478func (tunnel *Tunnel) GetTunnelsByClientId(responseWrite http.ResponseWriter, request *http.Request, params httprouter.Params) {479 clientId := request.FormValue("client_id")480 if clientId == "" {481 jsonError(responseWrite, "client_id is error!", nil)482 return483 }484 db := G.DB()485 var rs *mysql.ResultSet486 rs, err := db.Query(db.AR().From("tunnel").Where(map[string]interface{}{487 "client_id": clientId,488 "is_delete": 0,489 }))490 if err != nil {491 jsonError(responseWrite, err.Error(), nil)492 return493 }494 jsonSuccess(responseWrite, "ok", rs.Rows())495}496//get tunnel by server_id497//method : GET498//params : server_id499func (tunnel *Tunnel) GetTunnelsByServerId(responseWrite http.ResponseWriter, request *http.Request, params httprouter.Params) {500 serverId := request.FormValue("server_id")501 if serverId == "" {502 jsonError(responseWrite, "server_id is error!", nil)503 return504 }505 db := G.DB()506 var rs *mysql.ResultSet507 rs, err := db.Query(db.AR().From("tunnel").Where(map[string]interface{}{508 "client_id": serverId,509 "is_delete": 0,510 }))511 if err != nil {512 jsonError(responseWrite, err.Error(), nil)513 return514 }515 jsonSuccess(responseWrite, "ok", rs.Rows())516}517//open tunnel518//method : GET519//params : tunnel_id520func (tunnel *Tunnel) TunnelOpen(responseWrite http.ResponseWriter, request *http.Request, params httprouter.Params) {521 tunnelId := request.FormValue("tunnel_id")522 if tunnelId == "" {523 jsonError(responseWrite, "tunnel_id is error!", nil)524 return525 }526 db := G.DB()527 var rs *mysql.ResultSet528 rs, err := db.Query(db.AR().From("tunnel").Where(map[string]interface{}{529 "tunnel_id": tunnelId,530 "is_delete": 0,531 }).Limit(0, 1))532 if err != nil {533 jsonError(responseWrite, err.Error(), nil)534 return535 }536 if rs.Len() == 0 {537 jsonError(responseWrite, "隧道不存在", nil)538 }539 tunnelValue := rs.Row()540 clientId := tunnelValue["client_id"]541 serverId := tunnelValue["server_id"]542 //clusterId := tunnelValue["cluster_id"]543 //client_id 存在544 rs, err = db.Query(db.AR().From("client").Where(map[string]interface{}{545 "client_id": clientId,546 "is_delete": 0,547 }).Limit(0, 1))548 if err != nil {549 jsonError(responseWrite, err.Error(), nil)550 return551 }552 if rs.Len() == 0 {553 jsonError(responseWrite, "client 不存在", nil)554 return555 }556 //clientValue := rs.Row()557 //server_id 存在558 rs, err = db.Query(db.AR().From("server").Where(map[string]interface{}{559 "server_id": serverId,560 "is_delete": 0,561 }).Limit(0, 1))562 if err != nil {563 jsonError(responseWrite, err.Error(), nil)564 return565 }566 if rs.Len() == 0 {567 jsonError(responseWrite, "server 不存在", nil)568 return569 }570 //serverValue := rs.Row()571 //client 部署在线572 rs, err = db.Query(db.AR().From("online").Where(map[string]interface{}{573 "cs_id": clientId,574 "cs_type": "client",575 }).Limit(0, 1))576 if err != nil {577 jsonError(responseWrite, err.Error(), nil)578 return579 }580 if rs.Len() == 0 {581 jsonError(responseWrite, "client 未部署", nil)582 return583 }584 //server 部署在线585 rs, err = db.Query(db.AR().From("online").Where(map[string]interface{}{586 "cs_id": serverId,587 "cs_type": "server",588 }).Limit(0, 1))589 if err != nil {590 jsonError(responseWrite, err.Error(), nil)591 return592 }593 if rs.Len() == 0 {594 jsonError(responseWrite, "server 未部署", nil)595 return596 }597 //查找 cluster ip598 clusterId := rs.Row()["cluster_id"]599 rs, err = db.Query(db.AR().From("cluster").Where(map[string]interface{}{600 "cluster_id": clusterId,601 }).Limit(0, 1))602 if err != nil {603 jsonError(responseWrite, err.Error(), nil)604 return605 }606 if(rs.Len() == 0) {607 jsonError(responseWrite, "cluster 不存在", nil)608 return609 }610 //clusterIp := rs.Row()["ip"]611 //tunnel 开启请求地址612 //tunnelOpenUri := strings.Replace("http://10.100.93.52:", cfg.GetString("uri.tunnel_open"), clusterIp, 1)613 tunnelOpenUri := "https://10.100.93.52:37080/port/open"614 //:TunnelID/:ServerToken/:ServerBindIP/:ServerListenPort/:ClientToken/:ClientLocalHost/:ClientLocalPort/:Protocol615 url := tunnelOpenUri + "/" +616 tunnelValue["tunnel_id"] + "/" +617 //serverValue["server_token"] + "/" +618 "SQ5UjZqd05RXC3jZbvwusJD5mBM7nmEv" + "/" +619 tunnelValue["server_listen_ip"] + "/" +620 tunnelValue["server_listen_port"] + "/" +621 //clientValue["client_token"] + "/" +622 "y6yNbPG8zirV83dt85o99HBSIjOHOcqy" + "/" +623 tunnelValue["client_local_host"] + "/" +624 tunnelValue["client_local_port"] + "/" +625 tunnelValue["protocol"] + "/" +626 "0"627 fmt.Println(url)628 fmt.Printf("url233333: %s\n",url)629 body, _, err := at_common.HttpGet(url)630 if err != nil {631 jsonError(responseWrite, err.Error(), nil)632 return633 }634 type Response struct {635 Code int636 Message string637 Data interface{}638 }639 var res Response640 json.Unmarshal(body, &res)641 if res.Data == 0 {642 jsonError(responseWrite, res.Message, nil)643 return644 }645 //修改tunnel状态646 tunnelUpdateValue := map[string]interface{}{647 "status": 1,648 "is_open": 1,649 "update_time": time.Now().Unix(),650 }651 rs, err = db.Exec(db.AR().Update("tunnel", tunnelUpdateValue, map[string]interface{}{652 "tunnel_id": tunnelId,653 }))654 if err != nil {655 jsonError(responseWrite, err.Error(), nil)656 return657 }658 jsonSuccess(responseWrite, "开启隧道成功", nil)659}660//close tunnel661//method : GET662//params : tunnel_id663func (tunnel *Tunnel) TunnelClose(responseWrite http.ResponseWriter, request *http.Request, params httprouter.Params) {664 fmt.Printf("tunnelClose222\n")665 tunnelId := request.FormValue("tunnel_id")666 if tunnelId == "" {667 jsonError(responseWrite, "tunnel_id is error!", nil)668 return669 }670 db := G.DB()671 var rs *mysql.ResultSet672 rs, err := db.Query(db.AR().From("tunnel").Where(map[string]interface{}{673 "tunnel_id": tunnelId,674 "is_delete": 0,675 }).Limit(0, 1))676 if err != nil {677 jsonError(responseWrite, err.Error(), nil)678 return679 }680 if rs.Len() == 0 {681 jsonError(responseWrite, "隧道不存在", nil)682 return683 }684 //查找 cluster ip685 clusterId := rs.Row()["cluster_id"]686 rs, err = db.Query(db.AR().From("cluster").Where(map[string]interface{}{687 "cluster_id": clusterId,688 }).Limit(0, 1))689 if err != nil {690 jsonError(responseWrite, err.Error(), nil)691 return692 }693 if(rs.Len() == 0) {694 jsonError(responseWrite, "cluster 不存在", nil)695 return696 }697 clusterIp := rs.Row()["ip"]698 //tunnel 关闭请求地址699 tunnelCloseUri := strings.Replace("{host}", cfg.GetString("uri.tunnel_close"), clusterIp, 1)700 type Response struct {701 Code int702 Message string703 Data interface{}704 }705 var res Response706 url := tunnelCloseUri + "/" + tunnelId707 body, _, err := at_common.HttpGet(url)708 if err != nil {709 jsonError(responseWrite, err.Error(), nil)710 return711 }712 json.Unmarshal(body, &res)713 if res.Data == 0 {714 jsonError(responseWrite, res.Message, nil)715 return716 }717 jsonSuccess(responseWrite, "隧道关闭成功", nil)718}719//tunnel status720//method : GET721//params : tunnel_id722func (tunnel *Tunnel) TunnelStatus(responseWrite http.ResponseWriter, request *http.Request, params httprouter.Params) {723 tunnelId := request.FormValue("tunnel_id")724 if tunnelId == "" {725 jsonError(responseWrite, "tunnel_id is error!", nil)726 return727 }728 db := G.DB()729 var rs *mysql.ResultSet730 rs, err := db.Query(db.AR().From("tunnel").Where(map[string]interface{}{731 "tunnel_id": tunnelId,732 "is_delete": 0,733 }).Limit(0, 1))734 if err != nil {735 jsonError(responseWrite, err.Error(), nil)736 return737 }738 if rs.Len() == 0 {739 jsonError(responseWrite, "隧道不存在", nil)740 return741 }742 //查找 cluster ip743 clusterId := rs.Row()["cluster_id"]744 rs, err = db.Query(db.AR().From("cluster").Where(map[string]interface{}{745 "cluster_id": clusterId,746 }).Limit(0, 1))747 if err != nil {748 jsonError(responseWrite, err.Error(), nil)749 return750 }751 if(rs.Len() == 0) {752 jsonError(responseWrite, "cluster 不存在", nil)753 return754 }755 clusterIp := rs.Row()["ip"]756 //tunnel 关闭请求地址757 tunnelStatusUri := strings.Replace("{host}", cfg.GetString("uri.tunnel_status"), clusterIp, 1)758 type Response struct {759 Code int760 Message string761 Data interface{}762 }763 var res Response764 url := tunnelStatusUri + "/" + tunnelId765 body, _, err := at_common.HttpGet(url)766 if err != nil {767 jsonError(responseWrite, err.Error(), nil)768 return769 }770 json.Unmarshal(body, &res)771 if res.Data == 0 {772 jsonError(responseWrite, res.Message, nil)773 return774 }775 jsonSuccess(responseWrite, "ok", res.Message)776}...

Full Screen

Full Screen

json-error.go

Source:json-error.go Github

copy

Full Screen

2import (3 "strconv"4)5type (6 // JSONError is a struct representation of JSON error as defined in https://jsonapi.org/format/#error-objects7 JSONError struct {8 // ID is a unique identifier for this particular occurrence of the problem9 ID string `json:"id,omitempty"`10 // Links is a string or a Link object that points to more details about the error11 Links map[string]interface{} `json:"links,omitempty"`12 // Status the HTTP status code expressed as a string13 Status string `json:"status,omitempty"`14 // Code is an application specific error code expressed as a string15 Code string `json:"code,omitempty"`16 // Title is a short, human-readable summary of the problem. SHOULD NOT change from occurrence to occurrence of the17 // same problem18 Title string `json:"title,omitempty"`19 // Detail is a human-readable explaination specific to this occurrence of the problem20 Detail string `json:"detail,omitempty"`21 // Source is an object containing references to the source of the error22 Source Source `json:"source,omitempty"`23 // Meta contains non standard meta-information about the error24 Meta map[string]interface{} `json:"meta,omitempty"`25 }26 // Link represents a link object27 Link struct {28 // HREF specifies the URL29 HREF string `json:"href"`30 // Meta contains non standard meta-information about the link31 Meta map[string]interface{} `json:"meta,omitempty"`32 }33 // Source is an object containing reference to the source of the error34 Source struct {35 Pointer string `json:"pointer,omitempty"`36 Parameter string `json:"parameter,omitempty"`37 Other interface{} `json:",inline,omitempty"`38 }39 // JSONErrorBuilder is a convenience builder for creating a new JSONError40 JSONErrorBuilder struct {41 *JSONError42 }43)44// ErrorBuilder is a convenience function for building new JSONError45func ErrorBuilder() *JSONErrorBuilder {46 return &JSONErrorBuilder{&JSONError{}}47}48// ID sets the id of the JSONError49func (b *JSONErrorBuilder) ID(id string) *JSONErrorBuilder {50 b.JSONError.ID = id51 return b52}53// AddSimpleLink adds a simple link with a string url54func (b *JSONErrorBuilder) AddSimpleLink(key, url string) *JSONErrorBuilder {55 if b.JSONError.Links == nil {56 b.JSONError.Links = make(map[string]interface{})57 }58 b.JSONError.Links[key] = url59 return b60}61// AddLink Adds an Link62func (b *JSONErrorBuilder) AddLink(key, url string, meta map[string]interface{}) *JSONErrorBuilder {63 if b.JSONError.Links == nil {64 b.JSONError.Links = make(map[string]interface{})65 }66 b.JSONError.Links[key] = Link{67 HREF: url,68 Meta: meta,69 }70 return b71}72// Status sets the HTTP status of the error73func (b *JSONErrorBuilder) Status(status int) *JSONErrorBuilder {74 b.JSONError.Status = strconv.Itoa(status)75 return b76}77// Code sets the application specific code78func (b *JSONErrorBuilder) Code(code string) *JSONErrorBuilder {79 b.JSONError.Code = code80 return b81}82// Title sets the summary of the error83func (b *JSONErrorBuilder) Title(title string) *JSONErrorBuilder {84 b.JSONError.Title = title85 return b86}87// Detail sets the detailed error88func (b *JSONErrorBuilder) Detail(detail string) *JSONErrorBuilder {89 b.JSONError.Detail = detail90 return b91}92// SourcePointer sets the pointer of the request body to where the error occured93func (b *JSONErrorBuilder) SourcePointer(pointer string) *JSONErrorBuilder {94 b.JSONError.Source = Source{95 Pointer: pointer,96 }97 return b98}99// SourceParameter sets the name of the header/path/query parameter that caused the error100func (b *JSONErrorBuilder) SourceParameter(parameter string) *JSONErrorBuilder {101 b.JSONError.Source = Source{102 Parameter: parameter,103 }104 return b105}106// Source sets the source of the error107func (b *JSONErrorBuilder) Source(pointer, parameter string, other interface{}) *JSONErrorBuilder {108 b.JSONError.Source = Source{109 Pointer: pointer,110 Parameter: parameter,111 Other: other,112 }113 return b114}115// AddMeta adds metadata to the error116func (b *JSONErrorBuilder) AddMeta(key string, value interface{}) *JSONErrorBuilder {117 if b.JSONError.Meta == nil {118 b.JSONError.Meta = map[string]interface{}{}119 }120 b.JSONError.Meta[key] = value121 return b122}123// Build creates the JSONError124func (b *JSONErrorBuilder) Build() JSONError {125 return *b.JSONError126}...

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import (2type jsonerror struct {3}4func (e *jsonerror) Error() string {5 return fmt.Sprintf("%d: %s", e.Code, e.Message)6}7func main() {8 err := &jsonerror{Code: 42, Message: "Can't find answer"}9 b, _ := json.Marshal(err)10 fmt.Println(string(b))11}12{"code":42,"message":"Can't find answer"}

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "encoding/json"3func main() {4 var jsonBlob = []byte(`{"num": 6.13, "strs": ["a", "b"]}`)5 var data interface{}6 err := json.Unmarshal(jsonBlob, &data)7 if err != nil {8 fmt.Println("error:", err)9 }10 fmt.Printf("%+v11}

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1func main() {2 err := jsonerror.New("invalid JSON")3 fmt.Println(err.Error())4}5func main() {6 err := jsonerror.New("invalid JSON")7 fmt.Println(err)8}9func main() {10 err := jsonerror.New("invalid JSON")11 fmt.Println(err.Error())12}13func main() {14 err := jsonerror.New("invalid JSON")15 fmt.Println(err.Error())16}17func main() {18 err := jsonerror.New("invalid JSON")19 fmt.Println(err.Error())20}21func main() {22 err := jsonerror.New("invalid JSON")23 fmt.Println(err.Error())24}25func main() {26 err := jsonerror.New("invalid JSON")27 fmt.Println(err.Error())28}29func main() {30 err := jsonerror.New("invalid JSON")31 fmt.Println(err.Error())32}33func main() {34 err := jsonerror.New("invalid JSON")35 fmt.Println(err.Error())36}37func main() {38 err := jsonerror.New("invalid JSON")39 fmt.Println(err.Error())40}41func main() {42 err := jsonerror.New("invalid JSON")43 fmt.Println(err.Error())44}45func main() {46 err := jsonerror.New("invalid JSON")47 fmt.Println(err.Error())48}49func main() {50 err := jsonerror.New("invalid JSON")51 fmt.Println(err.Error())52}

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 err := errors.New("new error")4 fmt.Println(err.Error())5}6import (7func main() {8 err := errors.New("new error")9 fmt.Println(err)10}11import (12func main() {13 err := errors.New("new error")14 fmt.Println(errors.Is(err, errors.New("new error")))15}16import (17func main() {18 err := errors.New("new error")19 fmt.Println(errors.As(err, &target))20}21import (22func main() {23 err := errors.New("new error")24 fmt.Println(errors.Unwrap(err))25}26import (27func main() {28 err := errors.New("new error")29 fmt.Println(errors.Is(err, nil))30}31import (32func main() {33 err := errors.New("new error")34 fmt.Println(errors.Is(nil, err))35}36import (37func main() {38 err := errors.New("new error")39 fmt.Println(errors.Is(nil, nil))40}41import (42func main() {43 err := errors.New("new error

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1func main() {2 err = jsonerror.New("error message")3 fmt.Println(err.Error())4}5func main() {6 err = jsonerror.New("error message")7 fmt.Println(err)8}9func main() {10 err = jsonerror.New("error message")11 fmt.Println(&err)12}13func main() {14 err = jsonerror.New("error message")15 fmt.Println(&err.Error())16}17func main() {18 err = jsonerror.New("error message")19 fmt.Println(&err.Error())20}21func main() {22 err = jsonerror.New("error message")23 fmt.Println(err.Error())24}25func main() {26 err = jsonerror.New("error message")27 fmt.Println(err.Error())28}29func main() {30 err = jsonerror.New("error message")31 fmt.Println(&err.Error())32}33func main() {34 err = jsonerror.New("error message")35 fmt.Println(&err.Error())36}37func main() {38 err = jsonerror.New("error message")39 fmt.Println(err.Error())40}

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import (2type jsonerror struct {3}4func main() {5 b, _ := json.Marshal(error)6 fmt.Println(string(b))7}8{"error":"Error in parsing json"}9import (10type jsonerror struct {11}12func main() {13 data := `{"error":"Error in parsing json"}`14 json.Unmarshal([]byte(data), &error)15 fmt.Println(error.Err)16}17import (18type jsonerror struct {19}20func main() {21 b, _ := json.MarshalIndent(error, "", " ")22 fmt.Println(string(b))23}24{25}26import (27type jsonerror struct {28}29func main() {30 data := `{"error":"Error in parsing json"}`31 json.NewDecoder(strings.NewReader(data)).Decode(&error)32 fmt.Println(error.Err)33}34import (35type jsonerror struct {36}

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 var jsonStr = []byte(`{"message":"invalid character ' ' in string escape code"}`)4 err = json.Unmarshal(jsonStr, &err)5 if err != nil {6 fmt.Println(err)7 }8}9import (10func main() {11 var jsonStr = []byte(`{"message":"invalid character ' ' in string escape code"}`)12 err = json.Unmarshal(jsonStr, &err)13 if err != nil {14 fmt.Println(err.Error())15 }16}17import (18func main() {19 var jsonStr = []byte(`{"message":"invalid character ' ' in string escape code"}`)20 err = json.Unmarshal(jsonStr, &err)21 if err != nil {22 fmt.Println(err.Error())23 }24}25import (26func main() {27 var jsonStr = []byte(`{"message":"invalid character ' ' in string escape code"}`)28 err = json.Unmarshal(jsonStr, &err)29 if err != nil {30 fmt.Println(err.Error())31 }32}33import (34func main() {35 var jsonStr = []byte(`{"message":"invalid character ' ' in string escape code"}`)36 err = json.Unmarshal(jsonStr, &err)37 if err != nil {38 fmt.Println(err.Error())39 }40}41import (42func main() {

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1func main() {2 fmt.Println(err.Error())3}4func main() {5 fmt.Println(err)6}7{100 Error 100}8func main() {9 fmt.Println(err.Error())10 fmt.Println(err)11}12{100 Error 100}13func main() {14 fmt.Println(err.Error())15 fmt.Println(err)16 fmt.Println(err.Error())17}18{100 Error 100}19func main() {20 fmt.Println(err.Error())21 fmt.Println(err)22 fmt.Println(err.Error())23 fmt.Println(err)24}25{100 Error 100}26{100 Error 100}27func main() {28 fmt.Println(err.Error())29 fmt.Println(err)30 fmt.Println(err.Error())31 fmt.Println(err)32 fmt.Println(err.Error())33}34{100 Error 100}35{100 Error 100}36func main() {37 fmt.Println(err.Error())38 fmt.Println(err

Full Screen

Full Screen

Error

Using AI Code Generation

copy

Full Screen

1jsonerror := jsonerror{2}3log.Println(jsonerror.Error())4jsonerror := jsonerror{5}6log.Println(jsonerror.Error())7jsonerror := jsonerror{8}9log.Println(jsonerror.Error())10jsonerror := jsonerror{11}12log.Println(jsonerror.Error())13jsonerror := jsonerror{14}15log.Println(jsonerror.Error())16jsonerror := jsonerror{17}18log.Println(jsonerror.Error())19jsonerror := jsonerror{20}21log.Println(jsonerror.Error())22jsonerror := jsonerror{23}24log.Println(jsonerror.Error())25jsonerror := jsonerror{26}27log.Println(jsonerror.Error())28jsonerror := jsonerror{29}30log.Println(jsonerror.Error())31jsonerror := jsonerror{32}33log.Println(jsonerror.Error())34jsonerror := jsonerror{

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.

Run Selenoid automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful