valyala / fasthttp

Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http
MIT License
21.66k stars 1.75k forks source link

I have rawCookies := "cookie1=value1;cookie2=value2", would like to do the equivalent below for ctx.Request.Header #1553

Closed kolinfluence closed 1 year ago

kolinfluence commented 1 year ago

I have rawCookies := "cookie1=value1;cookie2=value2", would like to do the equivalent below for ctx.Request.Header ...for fasthttp

how do i get it done? by the way, i'm using HostClient to send and realised some error (when nginx accepts as input). just please help convert the http to fasthttp attached bottom code will do. thx

just to mention, i've also checked: https://github.com/valyala/fasthttp/issues/137 https://github.com/valyala/fasthttp/issues/740 https://github.com/valyala/fasthttp/issues/446 which is not what i want.

package main

import (
    "bufio"
    "fmt"
    "net/http"
    "strings"
)

func main() {
    rawCookies := "cookie1=value1;cookie2=value2"
    rawRequest := fmt.Sprintf("GET / HTTP/1.0\r\nCookie: %s\r\n\r\n", rawCookies)

    req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(rawRequest)))

    if err == nil {
        cookies := req.Cookies()
        fmt.Println(cookies)
    }
}
erikdubbelboer commented 1 year ago

That would translate into:

package main

import (
    "bufio"
    "fmt"
    "strings"

    "github.com/valyala/fasthttp"
)

func main() {
    rawCookies := "cookie1=value1;cookie2=value2"
    rawRequest := fmt.Sprintf("GET / HTTP/1.0\r\nCookie: %s\r\n\r\n", rawCookies)

    req := fasthttp.Request{}
    err := req.Read(bufio.NewReader(strings.NewReader(rawRequest)))

    if err == nil {
        req.Header.VisitAllCookie(func(key, value []byte) {
            fmt.Println(string(key), string(value))
        })
    }
}
kolinfluence commented 1 year ago

hi @erikdubbelboer , thx

if i have just rawCookies := "cookie1=value1;cookie2=value2" how do i make it into req as cookies?

erikdubbelboer commented 1 year ago

I'm not sure I understand. If you just want to parse cookies I would use something else that is specifically build for that.

kolinfluence commented 1 year ago

@erikdubbelboer thx again. it was a small error on my part. fixed it. thank you.