package main
import (
"context"
"fmt"
"io"
"github.com/fastly/compute-sdk-go/fsthttp"
)
const Backend = "origin_0"
func main() {
fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
c, err := r.Cookie("myCookie")
if err != nil {
w.WriteHeader(fsthttp.StatusBadGateway)
fmt.Fprintln(w, err)
return
}
FilterClientCookies(r, "myCookie")
resp, err := r.Send(ctx, Backend)
if err != nil {
w.WriteHeader(fsthttp.StatusBadGateway)
fmt.Fprintln(w, err)
return
}
fsthttp.SetCookie(resp.Header, &fsthttp.Cookie{
Name: "myCookie",
Value: "foo",
Path: "/",
MaxAge: 60,
})
resp.Header.Add("Set-Cookie", "mySecondCookie=bar; httpOnly")
resp.Header.Set("Cache-Control", "no-store, private")
fmt.Println(resp.Header.Keys())
w.Header().Reset(resp.Header)
w.WriteHeader(resp.StatusCode)
if c.Value != "" {
fmt.Fprintf(w, "The value of myCookie is %q\n", c.Value)
}
io.Copy(w, resp.Body)
})
}
func FilterClientCookies(r *fsthttp.Request, names ...string) {
filter := make(map[string]struct{}, len(names))
for _, name := range names {
filter[name] = struct{}{}
}
cookies := r.Cookies()
r.Header.Del("Cookie")
for _, c := range cookies {
if _, ok := filter[c.Name]; ok {
continue
}
r.Header.Add("Cookie", fmt.Sprintf("%s=%s", c.Name, c.Value))
}
}