How to use Throw method of common Package

Best K6 code snippet using common.Throw

new_post.go

Source:new_post.go Github

copy

Full Screen

1package handler2import (3 "bytes"4 "crypto/sha1"5 "fmt"6 "image"7 _ "image/gif"8 "image/jpeg"9 _ "image/png"10 "io"11 "io/ioutil"12 "log"13 "math/rand"14 "mime"15 "mime/multipart"16 "net"17 "net/url"18 "path/filepath"19 "strconv"20 "strings"21 "sync"22 "time"23 "unsafe"24 "github.com/coyove/iis/common"25 "github.com/coyove/iis/common/compress"26 "github.com/coyove/iis/dal"27 "github.com/coyove/iis/ik"28 "github.com/coyove/iis/middleware"29 "github.com/coyove/iis/model"30 "github.com/gin-gonic/gin"31 "github.com/nfnt/resize"32)33func hashIP(g *gin.Context) string {34 ip := append(net.IP{}, g.MustGet("ip").(net.IP)...)35 if len(ip) == net.IPv4len {36 ip[3] = 0 // \2437 } else if len(ip) == net.IPv6len {38 ip4 := ip.To4()39 if ip4 != nil {40 ip = ip441 ip[3] = 042 } else {43 copy(ip[10:], "\x00\x00\x00\x00\x00\x00") // \8044 }45 }46 return ip.String() + "/" + strconv.FormatInt(time.Now().Unix(), 36)47}48func PostBox(g *gin.Context) {49 if p := g.Query("p"); p == "" {50 g.Redirect(302, "/t")51 } else {52 g.Redirect(302, "/S/"+p[1:])53 }54}55func APINew(g *gin.Context) {56 throw(checkIP(g), "")57 g.Set("allow-api", true)58 var (59 replyTo = g.PostForm("parent")60 content = common.SoftTrunc(g.PostForm("content"), int(common.Cfg.MaxContent))61 image = common.DetectMedia(g.PostForm("media"))62 replyLock, _ = strconv.Atoi(g.PostForm("reply_lock"))63 pastebin = false64 )65 u := dal.GetUserByContext(g)66 if u == nil {67 throw(g.PostForm("api2_uid") != "", "user_not_found")68 throw(replyTo != "", "cannot_reply")69 u = &model.User{ID: "pastebin" + strconv.Itoa(rand.Intn(10))}70 image, replyLock, pastebin = "", 0, true71 if content == "" {72 // curl -F 'content=@file'73 f, err := g.FormFile("content")74 throw(err, "multipart_error")75 rd, err := f.Open()76 throw(err, "multipart_error")77 defer rd.Close()78 tmp, _ := ioutil.ReadAll(io.LimitReader(rd, common.Cfg.MaxContent))79 content = *(*string)(unsafe.Pointer(&tmp))80 }81 }82 if replyTo == "" {83 throw(len(content) < 3 && image == "", "content_too_short")84 }85 a := &model.Article{86 Author: u.ID,87 Content: content,88 Media: image,89 IP: hashIP(g),90 Asc: byte(common.BoolInt(g.PostForm("asc") != "")),91 NSFW: g.PostForm("nsfw") != "",92 Anonymous: replyTo == "" && g.PostForm("anon") != "", // anonymous replies are meaningless93 ReplyLockMode: byte(replyLock),94 CreateTime: time.Now(),95 Extras: map[string]string{},96 T_StickOnTop: g.PostForm("stick_on_top") != "",97 }98 if u.IsAPI() {99 a.Extras["is_bot"], a.Extras["bot"] = "1", g.PostForm("bot")100 }101 if pastebin {102 // Pastebin won't go into master timeline103 a.PostOptions |= model.PostOptionNoMasterTimeline104 a.History = fmt.Sprintf("{pastebin_by:%q}", g.ClientIP())105 throw(common.Err2(dal.Post(a, u)), "")106 g.String(200, a.ID)107 return108 }109 if u.FollowApply != 0 {110 // If I want to control & filter my followers, then I would definitly not want my feeds found by non-followers111 a.PostOptions |= model.PostOptionNoSearch112 }113 var av ArticleView114 if replyTo == "" {115 if g.PostForm("poll") == "1" {116 handlePollContent(a)117 }118 if g.PostForm("no_master") == "1" {119 a.PostOptions |= model.PostOptionNoMasterTimeline120 }121 a2, err := dal.Post(a, u)122 throw(err, "")123 av.from(a2, aTimeline, u)124 } else {125 if g.PostForm("no_timeline") == "1" || strings.Contains(content, "#ReportThis") {126 a.PostOptions |= model.PostOptionNoSearch127 a.PostOptions |= model.PostOptionNoTimeline128 }129 if g.PostForm("append") == "1" {130 throw(common.Err2(dal.DoUpdateArticle(replyTo, func(parent *model.Article) error {131 if !(u.IsMod() || parent.Author == u.ID) {132 return fmt.Errorf("e:cannot_reply")133 }134 if parent.Author == u.ID {135 parent.Content += "\n" + a.Content136 } else {137 parent.Content += "\n[append]" + u.ID + "[/append]\n" + a.Content138 }139 parent.Content = common.SoftTrunc(parent.Content, int(common.Cfg.MaxContent))140 return nil141 })), "")142 }143 a2, err := dal.PostReply(replyTo, a, u)144 throw(err, "cannot_reply")145 av.from(a2, aReply, u)146 }147 okok(g, url.PathEscape(middleware.RenderTemplateString("row_content.html", av)))148}149func APIDeleteArticle(g *gin.Context) {150 u := throw(dal.GetUserByContext(g), "").(*model.User)151 throw(checkIP(g), "")152 throw(common.Err2(dal.DoUpdateArticle(g.PostForm("id"), func(a *model.Article) error {153 if u.ID != a.Author && !u.IsMod() {154 return fmt.Errorf("e:user_not_permitted")155 }156 a.Content = model.DeletionMarker157 a.Media = ""158 a.History += fmt.Sprintf("{delete_by:%s:%v}", u.ID, time.Now().Unix())159 if a.Parent != "" {160 go dal.DoUpdateArticle(a.Parent, func(a *model.Article) { a.Replies-- })161 }162 return nil163 })), "")164 okok(g)165}166func APIToggleNSFWArticle(g *gin.Context) {167 u := throw(dal.GetUserByContext(g), "").(*model.User)168 throw(checkIP(g), "")169 throw(common.Err2(dal.DoUpdateArticle(g.PostForm("id"), func(a *model.Article) error {170 if u.ID != a.Author && !u.IsMod() {171 return fmt.Errorf("e:user_not_permitted")172 }173 a.NSFW = !a.NSFW174 a.History += fmt.Sprintf("{nsfw_by:%s:%v}", u.ID, time.Now().Unix())175 return nil176 })), "")177 okok(g)178}179func APIToggleLockArticle(g *gin.Context) {180 u := throw(dal.GetUserByContext(g), "").(*model.User)181 throw(checkIP(g), "")182 v, _ := strconv.Atoi(g.PostForm("mode"))183 throw(common.Err2(dal.DoUpdateArticle(g.PostForm("id"), func(a *model.Article) error {184 if u.ID != a.Author && !u.IsMod() {185 return fmt.Errorf("e:user_not_permitted")186 }187 a.ReplyLockMode = byte(v)188 a.History += fmt.Sprintf("{lock_by:%s:%v}", u.ID, time.Now().Unix())189 return nil190 })), "")191 okok(g)192}193func APIDropTop(g *gin.Context) {194 u := throw(dal.GetUserByContext(g), "").(*model.User)195 throw(checkIP(g), "")196 throw(common.Err2(dal.DoUpdateArticle(ik.NewID(ik.IDAuthor, u.ID).String(), func(a *model.Article) {197 a.Extras["stick_on_top"] = ""198 })), "")199 okok(g)200}201func APIPoll(g *gin.Context) {202 u := throw(dal.GetUserByContext(g), "").(*model.User)203 throw(checkIP(g), "")204 a, err := dal.GetArticle(g.PostForm("id"))205 throw(err, "")206 throw(a.Extras["poll_title"] == "", "")207 pollID := "u/" + u.ID + "/poll/" + a.ID208 uc, err := dal.GetArticle(pollID)209 throw(err != nil && err != model.ErrNotExisted, "")210 if uc != nil && uc.Extras["choice"] != "" {211 // Clear old poll votes212 throw(a.Extras["poll_nochange"] != "", "poll_nochange")213 throw(common.Err2(dal.DoUpdateArticle(pollID, func(a *model.Article) {214 a.Extras["choice"] = ""215 })), "")216 oldChoices := strings.Split(uc.Extras["choice"], ",")217 throw(common.Err2(dal.DoUpdateArticle(a.ID, func(a *model.Article) {218 for _, key := range append(oldChoices, "poll_total") {219 v, _ := strconv.ParseInt(a.Extras[key], 10, 64)220 if v--; v < 0 {221 v = 0222 }223 a.Extras[key] = strconv.FormatInt(v, 10)224 }225 })), "")226 okok(g, common.RevRenderTemplateString("poll.html", []interface{}{a.ID, a.Extras}))227 return228 }229 // Cast new poll votes230 options, _ := strconv.Atoi(a.Extras["poll_options"])231 maxChoices, _ := strconv.Atoi(a.Extras["poll_max"])232 ttl := common.ParseDuration(a.Extras["poll_live"])233 newChoices := strings.Split(g.PostForm("choice"), ",")234 throw(len(newChoices) <= 0, "")235 throw(a.Extras["poll_multiple"] == "" && len(newChoices) > 1, "too_many_choices")236 throw(maxChoices != 0 && len(newChoices) > maxChoices, "too_many_choices")237 throw(ttl > 0 && a.CreateTime.Add(ttl).Before(time.Now()), "poll_closed")238 for _, c := range newChoices {239 throw(!strings.HasPrefix(c, "poll_"), "")240 c, _ := strconv.Atoi(c[5:])241 if c < 1 || c > options {242 log.Println(c, options, a.Extras)243 throw(true, "")244 }245 }246 throw(dal.ModKV().Set(pollID, (&model.Article{247 ID: pollID,248 Extras: map[string]string{"choice": strings.Join(newChoices, ",")},249 }).Marshal()), "")250 throw(common.Err2(dal.DoUpdateArticle(a.ID, func(a *model.Article) {251 for _, key := range append(newChoices, "poll_total") {252 v, _ := strconv.ParseInt(a.Extras[key], 10, 64)253 a.Extras[key] = strconv.FormatInt(v+1, 10)254 }255 })), "")256 {257 a2, _ := dal.GetArticle(a.ID)258 if a2 == nil {259 a2 = a // fallback260 }261 a2.Extras["poll_you_voted"] = strings.Join(newChoices, ",")262 okok(g, common.RevRenderTemplateString("poll.html", []interface{}{a2.ID, a2.Extras}))263 }264}265func APIUpload(g *gin.Context) {266 const IR = "ERROR"267 g.Set("error-as-500", true) // failure will be returned using 500 status code268 u := getUser(g)269 if u == nil {270 u, _ = dal.GetUserByToken(g.Query("api2_uid"), true)271 }272 throw(u, "INVALID_USER")273 throw(!ik.BAdd(u.ID), IR)274 d, params, err := mime.ParseMediaType(g.GetHeader("Content-Type"))275 throw(err, IR)276 throw(!(d == "multipart/form-data" || d == "multipart/mixed"), IR)277 boundary, ok := params["boundary"]278 throw(!ok, IR)279 mprd := multipart.NewReader(g.Request.Body, boundary)280 part, err := mprd.NextPart()281 throw(err, IR)282 fn := part.FileName()283 throw(fn == "", IR)284 buf, _ := ioutil.ReadAll(part)285 hash := sha1.Sum(buf)286 part.Close()287 img, ct, err := image.Decode(bytes.NewReader(buf))288 throw(err, IR)289 fn = strings.TrimSuffix(fn, filepath.Ext(fn))290 fn = fmt.Sprintf("%012x", hash[:6]) + "_" + strconv.Itoa(len(buf)/1000) + "k_" +291 compress.SafeStringForCompressString(fn) + "_" + u.ID + "." + ct292 var media string293 var err1, err2 error294 wg := sync.WaitGroup{}295 wg.Add(2)296 go func() { // upload thumbnail297 defer wg.Done()298 start := time.Now()299 m := resize.Resize(200, 0, img, resize.Bicubic)300 p := &bytes.Buffer{}301 err1 = jpeg.Encode(p, m, &jpeg.Options{Quality: 80})302 if err1 == nil {303 _, err1 = writeImageReader(u, fn+"-thumb", p.Bytes())304 }305 log.Println("resize took:", len(buf), "=>", p.Len(), time.Since(start).Seconds())306 }()307 go func() { // upload original image308 defer wg.Done()309 media, err2 = writeImageReader(u, fn, buf)310 }()311 wg.Wait()312 throw(err1, IR)313 throw(err2, IR)314 g.String(200, media)315}...

Full Screen

Full Screen

user_action.go

Source:user_action.go Github

copy

Full Screen

1package handler2import (3 "bytes"4 "strconv"5 "strings"6 "time"7 "github.com/coyove/iis/common"8 "github.com/coyove/iis/dal"9 "github.com/coyove/iis/ik"10 "github.com/coyove/iis/model"11 "github.com/gin-gonic/gin"12)13func APISignup(g *gin.Context) {14 var (15 username = sanUsername(g.PostForm("username"))16 email = common.SoftTrunc(g.PostForm("email"), 64)17 password = common.SoftTrunc(g.PostForm("password"), 32)18 )19 throw(len(username) < 3 || len(password) < 3, "id_too_short")20 throw(checkCaptcha(g), "")21 switch username := strings.ToLower(username); {22 case strings.HasPrefix(username, "master"), strings.HasPrefix(username, "admin"):23 throw(true, "duplicated_id")24 case strings.HasPrefix(username, strings.ToLower(common.Cfg.AdminName)):25 admin, _ := dal.GetUser(common.Cfg.AdminName)26 throw(admin != nil, "duplicated_id")27 }28 session := genSession()29 throw(dal.DoSignUp(username, hashPassword(password), email, session, hashIP(g)), "")30 tok := ik.MakeUserToken(username, session)31 g.SetCookie("id", tok, 365*86400, "", "", false, false)32 okok(g)33}34func APILogin(g *gin.Context) {35 throw(checkIP(g), "")36 u, _ := dal.GetUser(sanUsername(g.PostForm("username")))37 throw(u, "invalid_id_password")38 throw(!bytes.Equal(u.PasswordHash, hashPassword(g.PostForm("password"))), "invalid_id_password")39 throw(common.Err2(dal.DoUpdateUser(u.ID, func(u2 *model.User) {40 u2.DataIP = common.PushIP(u.DataIP, hashIP(g))41 u2.TLogin = uint32(time.Now().Unix())42 })), "")43 ttl := 044 if g.PostForm("remember") != "" {45 ttl = 365 * 8640046 }47 g.SetCookie("id", ik.MakeUserToken(u.ID, u.Session), ttl, "", "", false, false)48 okok(g)49}50func APIUserKimochi(g *gin.Context) {51 u := throw(dal.GetUserByContext(g), "").(*model.User)52 k, _ := strconv.Atoi(g.PostForm("k"))53 if k < 0 || k > 44 {54 k = 2555 }56 throw(common.Err2(dal.DoUpdateUser(u.ID, "Kimochi", byte(k))), "")57 okok(g)58}59func APISearch(g *gin.Context) {60 type p struct {61 ID string62 Display string63 IsTag bool64 }65 results := []p{}66 uids, _ := model.Search("su", g.PostForm("id"), 0, 10)67 for i := range uids {68 if u, _ := dal.GetUser(uids[i].Tag()); u != nil {69 results = append(results, p{Display: u.DisplayName(), ID: uids[i].Tag()})70 }71 }72 tags, _ := model.Search("st", g.PostForm("id"), 0, 10)73 for _, t := range tags {74 results = append(results, p{Display: "#" + t.Tag(), ID: t.Tag(), IsTag: true})75 }76 g.JSON(200, results)77}78func APINewCaptcha(g *gin.Context) {79 var p struct {80 UUID string81 Challenge string82 }83 p.UUID, p.Challenge = ik.MakeToken(g)84 g.JSON(200, p)85}86func APILike(g *gin.Context) {87 u := throw(dal.GetUserByContext(g), "").(*model.User)88 to := g.PostForm("to")89 throw(checkIP(g), "")90 throw(to == "", "")91 throw(dal.LikeArticle(u, to, g.PostForm("like") != ""), "")92 okok(g)93}94func APILogout(g *gin.Context) {95 u := dal.GetUserByContext(g)96 if u != nil {97 dal.DoUpdateUser(u.ID, "Session", "")98 g.SetCookie("id", ik.MakeUserToken("", ""), 365*86400, "", "", false, false)99 }100 okok(g)101}102func APIFollowBlock(g *gin.Context) {103 u, to := dal.GetUserByContext(g), g.PostForm("to")104 throw(u, "")105 throw(to == "" || u.ID == to, "")106 throw(checkIP(g), "")107 isTag := strings.HasPrefix(to, "#")108 switch g.PostForm("method") {109 case "follow":110 following := g.PostForm("follow") != ""111 if following && !isTag {112 throw(dal.IsBlocking(to, u.ID), "cannot_follow")113 }114 throw(dal.FollowUser(u.ID, to, following), "")115 if !isTag {116 toUser, _ := dal.WeakGetUser(to)117 if toUser != nil && toUser.FollowApply != 0 {118 g.Writer.Header().Add("X-Follow-Apply", "1")119 }120 }121 case "accept":122 throw(isTag, "cannot_accept_tag")123 throw(dal.AcceptUser(u.ID, to, true), "")124 // Given the situation that there may be A LOT applications received by one user125 g.Set("clear-ip-throt", true)126 default:127 throw(isTag, "cannot_block_tag")128 throw(dal.BlockUser(u.ID, to, g.PostForm("block") != ""), "")129 }130 okok(g)131}132func APIUpdateUserSettings(g *gin.Context) {133 u := throw(dal.GetUserByContext(g), "").(*model.User)134 switch {135 case g.PostForm("set-email") != "":136 throw(common.Err2(dal.DoUpdateUser(u.ID, "Email", common.SoftTrunc(g.PostForm("email"), 256))), "")137 case g.PostForm("set-autonsfw") != "":138 throw(common.Err2(dal.DoUpdateUser(u.ID, "ExpandNSFWImages", common.BoolInt(g.PostForm("autonsfw") != ""))), "")139 case g.PostForm("set-foldimg") != "":140 throw(common.Err2(dal.DoUpdateUser(u.ID, "FoldAllImages", common.BoolInt(g.PostForm("foldimg") != ""))), "")141 case g.PostForm("set-hl") != "":142 throw(common.Err2(dal.DoUpdateUser(u.ID, "HideLocation", common.BoolInt(g.PostForm("hl") != ""))), "")143 case g.PostForm("set-hide-likes") != "":144 throw(common.Err2(dal.DoUpdateUser(u.ID, "HideLikes", common.BoolInt(g.PostForm("hide-likes") != ""))), "")145 case g.PostForm("set-mfcm") != "":146 throw(common.Err2(dal.DoUpdateUser(u.ID, "NotifyFollowerActOnly", common.BoolInt(g.PostForm("mfcm") != ""))), "")147 case g.PostForm("set-description") != "":148 throw(common.Err2(dal.DoUpdateUser(u.ID, "Description", common.SoftTrunc(g.PostForm("description"), 512))), "")149 case g.PostForm("set-apisession") != "":150 apiToken := ik.MakeUserToken(u.ID, "api+"+genSession())151 throw(common.Err2(dal.DoUpdateUser(u.ID, "APIToken", apiToken)), "")152 okok(g, apiToken)153 return154 case g.PostForm("set-fw-accept") != "":155 throw(common.Err2(dal.DoUpdateUser(u.ID, func(u *model.User) {156 if g.PostForm("fw-accept") != "" {157 u.FollowApply = uint32(time.Now().Unix())158 } else {159 u.FollowApply = 0160 }161 })), "")162 case g.PostForm("set-custom-name") != "":163 name := g.PostForm("custom-name")164 if strings.Contains(strings.ToLower(name), "admin") && !u.IsAdmin() {165 name = strings.Replace(name, "admin", "nimda", -1)166 }167 name = common.SoftTruncDisplayWidth(name, 16)168 u2, err := dal.DoUpdateUser(u.ID, "CustomName", name)169 throw(err, "")170 model.IndexUser(u2)171 case g.PostForm("set-avatar") != "":172 throw(common.Err2(writeAvatar(u, g.PostForm("avatar"))), "")173 throw(common.Err2(dal.DoUpdateUser(u.ID, "Avatar", uint32(time.Now().Unix()))), "")174 }175 go dal.DoUpdateUser(u.ID, "DataIP", common.PushIP(u.DataIP, hashIP(g)))176 okok(g)177}178func APIUpdateUserPassword(g *gin.Context) {179 u := throw(dal.GetUserByContext(g), "").(*model.User)180 throw(checkIP(g), "")181 oldPassword := common.SoftTrunc(g.PostForm("old-password"), 32)182 newPassword := common.SoftTrunc(g.PostForm("new-password"), 32)183 throw(len(newPassword) < 3, "new_password_too_short")184 throw(!bytes.Equal(u.PasswordHash, hashPassword(oldPassword)), "old_password_invalid")185 throw(common.Err2(dal.DoUpdateUser(u.ID, "PasswordHash", hashPassword(newPassword))), "")186 okok(g)187}188func APIResetUserPassword(g *gin.Context) {189}190func APIClearInbox(g *gin.Context) {191 u := throw(dal.GetUserByContext(g), "").(*model.User)192 throw(dal.ClearInbox(u.ID), "")193 okok(g)194}...

Full Screen

Full Screen

encoding_test.go

Source:encoding_test.go Github

copy

Full Screen

1/*2 *3 * k6 - a next-generation load testing tool4 * Copyright (C) 2017 Load Impact5 *6 * This program is free software: you can redistribute it and/or modify7 * it under the terms of the GNU Affero General Public License as8 * published by the Free Software Foundation, either version 3 of the9 * License, or (at your option) any later version.10 *11 * This program is distributed in the hope that it will be useful,12 * but WITHOUT ANY WARRANTY; without even the implied warranty of13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the14 * GNU Affero General Public License for more details.15 *16 * You should have received a copy of the GNU Affero General Public License17 * along with this program. If not, see <http://www.gnu.org/licenses/>.18 *19 */20package encoding21import (22 "context"23 "testing"24 "github.com/dop251/goja"25 "github.com/stretchr/testify/assert"26 "go.k6.io/k6/js/common"27)28func TestEncodingAlgorithms(t *testing.T) {29 if testing.Short() {30 return31 }32 rt := goja.New()33 rt.SetFieldNameMapper(common.FieldNameMapper{})34 ctx := context.Background()35 ctx = common.WithRuntime(ctx, rt)36 rt.Set("encoding", common.Bind(rt, New(), &ctx))37 t.Run("Base64", func(t *testing.T) {38 t.Run("DefaultEnc", func(t *testing.T) {39 _, err := common.RunString(rt, `40 var correct = "aGVsbG8gd29ybGQ=";41 var encoded = encoding.b64encode("hello world");42 if (encoded !== correct) {43 throw new Error("Encoding mismatch: " + encoded);44 }`)45 assert.NoError(t, err)46 })47 t.Run("DefaultDec", func(t *testing.T) {48 _, err := common.RunString(rt, `49 var correct = "hello world";50 var decoded = encoding.b64decode("aGVsbG8gd29ybGQ=");51 if (decoded !== correct) {52 throw new Error("Decoding mismatch: " + decoded);53 }`)54 assert.NoError(t, err)55 })56 t.Run("DefaultUnicodeEnc", func(t *testing.T) {57 _, err := common.RunString(rt, `58 var correct = "44GT44KT44Gr44Gh44Gv5LiW55WM";59 var encoded = encoding.b64encode("こんにちは世界", "std");60 if (encoded !== correct) {61 throw new Error("Encoding mismatch: " + encoded);62 }`)63 assert.NoError(t, err)64 })65 t.Run("DefaultUnicodeDec", func(t *testing.T) {66 _, err := common.RunString(rt, `67 var correct = "こんにちは世界";68 var decoded = encoding.b64decode("44GT44KT44Gr44Gh44Gv5LiW55WM");69 if (decoded !== correct) {70 throw new Error("Decoding mismatch: " + decoded);71 }`)72 assert.NoError(t, err)73 })74 t.Run("StdEnc", func(t *testing.T) {75 _, err := common.RunString(rt, `76 var correct = "aGVsbG8gd29ybGQ=";77 var encoded = encoding.b64encode("hello world", "std");78 if (encoded !== correct) {79 throw new Error("Encoding mismatch: " + encoded);80 }`)81 assert.NoError(t, err)82 })83 t.Run("StdDec", func(t *testing.T) {84 _, err := common.RunString(rt, `85 var correct = "hello world";86 var decoded = encoding.b64decode("aGVsbG8gd29ybGQ=", "std");87 if (decoded !== correct) {88 throw new Error("Decoding mismatch: " + decoded);89 }`)90 assert.NoError(t, err)91 })92 t.Run("RawStdEnc", func(t *testing.T) {93 _, err := common.RunString(rt, `94 var correct = "aGVsbG8gd29ybGQ";95 var encoded = encoding.b64encode("hello world", "rawstd");96 if (encoded !== correct) {97 throw new Error("Encoding mismatch: " + encoded);98 }`)99 assert.NoError(t, err)100 })101 t.Run("RawStdDec", func(t *testing.T) {102 _, err := common.RunString(rt, `103 var correct = "hello world";104 var decoded = encoding.b64decode("aGVsbG8gd29ybGQ", "rawstd");105 if (decoded !== correct) {106 throw new Error("Decoding mismatch: " + decoded);107 }`)108 assert.NoError(t, err)109 })110 t.Run("URLEnc", func(t *testing.T) {111 _, err := common.RunString(rt, `112 var correct = "5bCP6aO85by-Li4=";113 var encoded = encoding.b64encode("小飼弾..", "url");114 if (encoded !== correct) {115 throw new Error("Encoding mismatch: " + encoded);116 }`)117 assert.NoError(t, err)118 })119 t.Run("URLDec", func(t *testing.T) {120 _, err := common.RunString(rt, `121 var correct = "小飼弾..";122 var decoded = encoding.b64decode("5bCP6aO85by-Li4=", "url");123 if (decoded !== correct) {124 throw new Error("Decoding mismatch: " + decoded);125 }`)126 assert.NoError(t, err)127 })128 t.Run("RawURLEnc", func(t *testing.T) {129 _, err := common.RunString(rt, `130 var correct = "5bCP6aO85by-Li4";131 var encoded = encoding.b64encode("小飼弾..", "rawurl");132 if (encoded !== correct) {133 throw new Error("Encoding mismatch: " + encoded);134 }`)135 assert.NoError(t, err)136 })137 t.Run("RawURLDec", func(t *testing.T) {138 _, err := common.RunString(rt, `139 var correct = "小飼弾..";140 var decoded = encoding.b64decode("5bCP6aO85by-Li4", "rawurl");141 if (decoded !== correct) {142 throw new Error("Decoding mismatch: " + decoded);143 }`)144 assert.NoError(t, err)145 })146 })147}...

Full Screen

Full Screen

Throw

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "github.com/GoLangTraining/01_package/stringutil"3func main() {4fmt.Println(stringutil.Reverse("!oG ,olleH"))5fmt.Println(stringutil.MyName)6stringutil.Throw()7}8import "fmt"9import "github.com/GoLangTraining/01_package/stringutil"10func main() {11fmt.Println(stringutil.Reverse("!oG ,olleH"))12fmt.Println(stringutil.MyName)13stringutil.Throw()14}15func Throw() {16fmt.Println("Throwing")17}

Full Screen

Full Screen

Throw

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World!")4 common.Throw("Error")5}6import (7func Throw(msg string) {8 fmt.Println(msg)9}

Full Screen

Full Screen

Throw

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World")4 common.Throw("Error")5}6import (7func Throw(message string) {8 fmt.Println("Error: " + message)9}

Full Screen

Full Screen

Throw

Using AI Code Generation

copy

Full Screen

1func main() {2 common.Throw("This is an error")3}4main.main()5import "fmt"6func Throw(message string) {7 fmt.Println(message)8 panic(message)9}

Full Screen

Full Screen

Throw

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World!")4 common.Throw("This is my first go package")5}6import (7func Throw(msg string) {8 fmt.Println("Message: " + msg)9}10import "github.com/pankajyadav/common"

Full Screen

Full Screen

Throw

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 err := exception.Throw("This is a test exception")4 if err != nil {5 fmt.Println(err)6 }7}8import (9func main() {10 err := exception.Throw("This is a test exception", 100)11 if err != nil {12 fmt.Println(err)13 }14}15import (16func main() {17 err := exception.Throw("This is a test exception", 100, "Error")18 if err != nil {19 fmt.Println(err)20 }21}22import (23func main() {24 err := exception.Throw("This is a test exception", 100, "Error", "stack")25 if err != nil {26 fmt.Println(err)27 }28}29import (30func main() {31 err := exception.Throw("This is a test exception", 100, "Error", "stack", "data")32 if err != nil {

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