How to use Header method of rod Package

Best Rod code snippet using rod.Header

hijack_test.go

Source:hijack_test.go Github

copy

Full Screen

...21 s.Mux.HandleFunc("/a", func(w http.ResponseWriter, r *http.Request) {22 if r.Method != http.MethodPost {23 panic("wrong http method")24 }25 g.Eq("header", r.Header.Get("Test"))26 b, err := ioutil.ReadAll(r.Body)27 g.E(err)28 g.Eq("a", string(b))29 g.HandleHTTP(".html", "test")(w, r)30 })31 s.Route("/b", "", "b")32 router := g.page.HijackRequests()33 defer router.MustStop()34 router.MustAdd(s.URL("/a"), func(ctx *rod.Hijack) {35 r := ctx.Request.SetContext(g.Context())36 r.Req().Header.Set("Test", "header") // override request header37 r.SetBody([]byte("test")) // override request body38 r.SetBody(123) // override request body39 r.SetBody(r.Body()) // override request body40 type MyState struct {41 Val int42 }43 ctx.CustomState = &MyState{10}44 g.Eq(http.MethodPost, r.Method())45 g.Eq(s.URL("/a"), r.URL().String())46 g.Eq(proto.NetworkResourceTypeXHR, ctx.Request.Type())47 g.Is(ctx.Request.IsNavigation(), false)48 g.Has(ctx.Request.Header("Origin"), s.URL())49 g.Len(ctx.Request.Headers(), 6)50 g.True(ctx.Request.JSONBody().Nil())51 // send request load response from real destination as the default value to hijack52 ctx.MustLoadResponse()53 g.Eq(200, ctx.Response.Payload().ResponseCode)54 // override status code55 ctx.Response.Payload().ResponseCode = http.StatusCreated56 g.Eq("4", ctx.Response.Headers().Get("Content-Length"))57 g.Has(ctx.Response.Headers().Get("Content-Type"), "text/html; charset=utf-8")58 // override response header59 ctx.Response.SetHeader("Set-Cookie", "key=val")60 // override response body61 ctx.Response.SetBody([]byte("test"))62 ctx.Response.SetBody("test")63 ctx.Response.SetBody(map[string]string{64 "text": "test",65 })66 g.Eq("{\"text\":\"test\"}", ctx.Response.Body())67 })68 router.MustAdd(s.URL("/b"), func(ctx *rod.Hijack) {69 panic("should not come to here")70 })71 router.MustRemove(s.URL("/b"))72 router.MustAdd(s.URL("/b"), func(ctx *rod.Hijack) {73 // transparent proxy74 ctx.MustLoadResponse()75 })76 go router.Run()77 g.page.MustNavigate(s.URL())78 g.Eq("201 test key=val", g.page.MustElement("#a").MustText())79 g.Eq("b", g.page.MustElement("#b").MustText())80}81func TestHijackContinue(t *testing.T) {82 g := setup(t)83 s := g.Serve().Route("/", ".html", `<body>ok</body>`)84 router := g.page.HijackRequests()85 defer router.MustStop()86 wg := &sync.WaitGroup{}87 wg.Add(1)88 router.MustAdd(s.URL("/a"), func(ctx *rod.Hijack) {89 ctx.ContinueRequest(&proto.FetchContinueRequest{})90 wg.Done()91 })92 go router.Run()93 g.page.MustNavigate(s.URL("/a"))94 g.Eq("ok", g.page.MustElement("body").MustText())95 wg.Wait()96}97func TestHijackMockWholeResponseEmptyBody(t *testing.T) {98 g := setup(t)99 router := g.page.HijackRequests()100 defer router.MustStop()101 router.MustAdd("*", func(ctx *rod.Hijack) {102 ctx.Response.SetBody("")103 })104 go router.Run()105 // needs to timeout or will hang when "omitempty" does not get removed from body in fulfillRequest106 timed := g.page.Timeout(time.Second)107 timed.MustNavigate(g.Serve().Route("/", ".txt", "OK").URL())108 g.Eq("", g.page.MustElement("body").MustText())109}110func TestHijackMockWholeResponseNoBody(t *testing.T) {111 // TODO: remove the skip112 t.Skip("Because of flaky test result")113 g := setup(t)114 router := g.page.HijackRequests()115 defer router.MustStop()116 // intercept and reply without setting a body117 router.MustAdd("*", func(ctx *rod.Hijack) {118 // we don't set any body here119 })120 go router.Run()121 // has to timeout as it will lock up the browser reading the reply.122 err := g.page.Timeout(time.Second).Navigate(g.Serve().Route("/", "").URL())123 g.Is(err, context.DeadlineExceeded)124}125func TestHijackMockWholeResponse(t *testing.T) {126 g := setup(t)127 router := g.page.HijackRequests()128 defer router.MustStop()129 router.MustAdd("*", func(ctx *rod.Hijack) {130 ctx.Response.SetHeader("Content-Type", mime.TypeByExtension(".html"))131 ctx.Response.SetBody("<body>ok</body>")132 })133 go router.Run()134 g.page.MustNavigate("http://test.com")135 g.Eq("ok", g.page.MustElement("body").MustText())136}137func TestHijackSkip(t *testing.T) {138 g := setup(t)139 s := g.Serve()140 router := g.page.HijackRequests()141 defer router.MustStop()142 wg := &sync.WaitGroup{}143 wg.Add(2)144 router.MustAdd(s.URL("/a"), func(ctx *rod.Hijack) {145 ctx.Skip = true146 wg.Done()147 })148 router.MustAdd(s.URL("/a"), func(ctx *rod.Hijack) {149 ctx.ContinueRequest(&proto.FetchContinueRequest{})150 wg.Done()151 })152 go router.Run()153 g.page.MustNavigate(s.URL("/a"))154 wg.Wait()155}156func TestHijackOnErrorLog(t *testing.T) {157 g := setup(t)158 s := g.Serve().Route("/", ".html", `<body>ok</body>`)159 router := g.page.HijackRequests()160 defer router.MustStop()161 wg := &sync.WaitGroup{}162 wg.Add(1)163 var err error164 router.MustAdd(s.URL("/a"), func(ctx *rod.Hijack) {165 ctx.OnError = func(e error) {166 err = e167 wg.Done()168 }169 ctx.ContinueRequest(&proto.FetchContinueRequest{})170 })171 go router.Run()172 g.mc.stub(1, proto.FetchContinueRequest{}, func(send StubSend) (gson.JSON, error) {173 return gson.New(nil), errors.New("err")174 })175 go func() {176 _ = g.page.Context(g.Context()).Navigate(s.URL("/a"))177 }()178 wg.Wait()179 g.Eq(err.Error(), "err")180}181func TestHijackFailRequest(t *testing.T) {182 g := setup(t)183 s := g.Serve().Route("/page", ".html", `<html>184 <body></body>185 <script>186 fetch('/a').catch(async (err) => {187 document.title = err.message188 })189 </script></html>`)190 router := g.browser.HijackRequests()191 defer router.MustStop()192 router.MustAdd(s.URL("/a"), func(ctx *rod.Hijack) {193 ctx.Response.Fail(proto.NetworkErrorReasonAborted)194 })195 go router.Run()196 g.page.MustNavigate(s.URL("/page")).MustWaitLoad()197 g.page.MustWait(`() => document.title === 'Failed to fetch'`)198 { // test error log199 g.mc.stub(1, proto.FetchFailRequest{}, func(send StubSend) (gson.JSON, error) {200 _, _ = send()201 return gson.JSON{}, errors.New("err")202 })203 _ = g.page.Navigate(s.URL("/a"))204 }205}206func TestHijackLoadResponseErr(t *testing.T) {207 g := setup(t)208 p := g.newPage().Context(g.Context())209 router := p.HijackRequests()210 defer router.MustStop()211 wg := &sync.WaitGroup{}212 wg.Add(1)213 router.MustAdd("http://test.com/a", func(ctx *rod.Hijack) {214 g.Err(ctx.LoadResponse(&http.Client{215 Transport: &MockRoundTripper{err: errors.New("err")},216 }, true))217 g.Err(ctx.LoadResponse(&http.Client{218 Transport: &MockRoundTripper{res: &http.Response{219 StatusCode: 200,220 Body: ioutil.NopCloser(&MockReader{err: errors.New("err")}),221 }},222 }, true))223 wg.Done()224 ctx.Response.Fail(proto.NetworkErrorReasonAborted)225 })226 go router.Run()227 _ = p.Navigate("http://test.com/a")228 wg.Wait()229}230func TestHijackResponseErr(t *testing.T) {231 g := setup(t)232 s := g.Serve().Route("/", ".html", `ok`)233 p := g.newPage().Context(g.Context())234 router := p.HijackRequests()235 defer router.MustStop()236 wg := &sync.WaitGroup{}237 wg.Add(1)238 router.MustAdd(s.URL("/a"), func(ctx *rod.Hijack) { // to ignore favicon239 ctx.OnError = func(err error) {240 g.Err(err)241 wg.Done()242 }243 ctx.MustLoadResponse()244 g.mc.stub(1, proto.FetchFulfillRequest{}, func(send StubSend) (gson.JSON, error) {245 res, _ := send()246 return res, errors.New("err")247 })248 })249 go router.Run()250 p.MustNavigate(s.URL("/a"))251 wg.Wait()252}253func TestHandleAuth(t *testing.T) {254 g := setup(t)255 s := g.Serve()256 // mock the server257 s.Mux.HandleFunc("/a", func(w http.ResponseWriter, r *http.Request) {258 u, p, ok := r.BasicAuth()259 if !ok {260 w.Header().Add("WWW-Authenticate", `Basic realm="web"`)261 w.WriteHeader(401)262 return263 }264 g.Eq("a", u)265 g.Eq("b", p)266 g.HandleHTTP(".html", `<p>ok</p>`)(w, r)267 })268 s.Route("/err", ".html", "err page")269 go g.browser.MustHandleAuth("a", "b")()270 page := g.newPage(s.URL("/a"))271 page.MustElementR("p", "ok")272 wait := g.browser.HandleAuth("a", "b")273 var page2 *rod.Page274 wait2 := utils.All(func() {275 page2, _ = g.browser.Page(proto.TargetCreateTarget{URL: s.URL("/err")})...

Full Screen

Full Screen

Header

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().Connect()4 headers := resp.Headers()5 fmt.Println(headers)6}7map[Content-Type:[text/html; charset=UTF-8] Date:[Mon, 14 Jun 2021 10:26:33 GMT] Expires:[-1] P3p:[CP="This is not a P3P policy! See g.co/p3phelp for more info."] Server:[gws] Set-Cookie:[1P_JAR=2021-06-14-10; expires=Wed, 14-Jul-

Full Screen

Full Screen

Header

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().Connect()4 headers := res.Headers()5 fmt.Println(headers)6 fmt.Println(headers["content-type"])7 fmt.Println(res.Header("content-type"))8}9map[Content-Type:[text/html; charset=ISO-8859-1] Content-Encoding:[gzip] Date:[Mon, 26 Apr 2021 16:05:49 GMT] Expires:[-1] Cache-Control:[private, max-age=0] Server:[gws] X-XSS-Protection:[0] X-Frame-Options:[SAMEORIGIN] Set-Cookie:[1P_JAR=2021-04-26-16; expires=Wed, 26-May-2021 16:05:49 GMT; path=/; domain=.google.com; Secure; SameSite=none, NID=204=QKQ2NkZsN1Zs0tX9gPZs7c0oBpRy7RmL1OYKwC3q0zQZ7V9Dvz0o7VrEiG7CnFjHkDwY8Qz1Zb7tZs9tX9M7e8pDn0RgRy1JhLwVjK3q0q7V9Zv9u9K7n; expires=Tue, 25-Aug-2021 16:05:49 GMT; path=/; domain=.google.com; HttpOnly; Secure; SameSite=none] Alt-Svc:[h3-29=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic="

Full Screen

Full Screen

Header

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(page.MustElement("input[name=q]").MustAttribute("name"))4 fmt.Println(page.MustElement("input[name=q]").MustAttribute("value"))5 fmt.Println(page.MustElement("input[name=q]").MustAttribute("type"))6 fmt.Println(page.MustElement("input[name=q]").MustAttribute("maxlength"))7 fmt.Println(page.MustElement("input[name=q]").MustAttribute("title"))8 fmt.Println(page.MustElement("input[name=q]").MustAttribute("spellcheck"))9 fmt.Println(page.MustElement("input[name=q]").MustAttribute("role"))10 fmt.Println(page.MustElement("input[name=q]").MustAttribute("dir"))11 fmt.Println(page.MustElement("input[name=q]").MustAttribute("class"))12 fmt.Println(page.MustElement("input[name=q]").MustAttribute("jsname"))13 fmt.Println(page.MustElement("input[name=q]").MustAttribute("jsaction"))14 fmt.Println(page.MustElement("input[name=q]").MustAttribute("data-ved"))15 fmt.Println(page.MustElement("input[name=q]").MustAttribute("autocomplete"))16 fmt.Println(page.MustElement("input[name=q]").MustAttribute("autocapitalize"))17 fmt.Println(page.MustElement("input[name=q]").MustAttribute("autocorrect"))18 fmt.Println(page.MustElement("input[name=q]").MustAttribute("aria-haspopup"))19 fmt.Println(page.MustElement("input[name=q]").MustAttribute("aria-autocomplete"))20 fmt.Println(page.MustElement("input[name=q]").MustAttribute("aria-expanded"))21 fmt.Println(page.MustElement("input[name=q]").MustAttribute("aria-label"))22 fmt.Println(page.MustElement("input[name=q]").MustAttribute("aria-activedescendant"))23 fmt.Println(page.MustElement("input[name=q]").MustAttribute("aria-owns"))24 fmt.Println(page.MustElement("input[name=q]").MustAttribute("aria-readonly"))25 fmt.Println(page.MustElement("input[name=q]").MustAttribute("aria-invalid"))26 fmt.Println(page.MustElement("input[name=q]").MustAttribute("aria-describedby"))27 fmt.Println(page.MustElement("input[name=q]").MustAttribute("aria-labelledby"))28 fmt.Println(page.MustElement("input[name=q]").MustAttribute("aria-required"))29 fmt.Println(page.MustElement("input[name=q]").MustAttribute("aria-placeholder"))30 fmt.Println(page.MustElement("input[name=q]").MustAttribute("aria

Full Screen

Full Screen

Header

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().Connect()4 page := browser.Page("")5 title := page.Title()6 fmt.Println(title)7 header := page.Header("User-Agent")8 fmt.Println(header)9}

Full Screen

Full Screen

Header

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().Connect()4 page := browser.Page("").WaitLoad()5 page.Element("#hplogo").WaitVisible()6 page.Element("#hplogo").Header("src")7 fmt.Println(page.Element("#hplogo").Header("src"))8}9import (10func main() {11 browser := rod.New().Connect()12 page := browser.Page("").WaitLoad()13 page.Element("#hplogo").WaitVisible()14 page.Element("#hplogo").Highlight()15 fmt.Println("Highlighted")16}17import (18func main() {19 browser := rod.New().Connect()20 page := browser.Page("").WaitLoad()21 page.Element("#hplogo").WaitVisible()22 page.Element("#hplogo").HTML()23 fmt.Println(page.Element("#hplogo").HTML())24}

Full Screen

Full Screen

Header

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "github.com/go-rod/rod"3func main() {4 browser := rod.New().Connect()5 defer browser.Close()6 page := browser.Page("")7 defer page.Close()8 title := page.Title()9 fmt.Println(title)10 url := page.URL()11 fmt.Println(url)12 header := page.Header()13 fmt.Println(header)14}15map[Content-Type:[text/html; charset=ISO-8859-1] Date:[Wed, 23 Jun 2021 12:00:30 GMT] Expires:[-1] P3p:[CP="This is not a P3P policy! See g.co/p3phelp for more info."] Server:[gws] X-Frame-Options:[SAMEORIGIN] X-Xss-Protect

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 Rod automation tests on LambdaTest cloud grid

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

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful