Created
January 22, 2022 14:32
-
-
Save bokunodev/8da0135140d9e554f0b8b6df3cccbd1b to your computer and use it in GitHub Desktop.
example cookie on differ ports
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module local.pc/sand | |
go 1.18 | |
require github.com/go-chi/chi/v5 v5.0.7 | |
require github.com/davecgh/go-spew v1.1.1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"log" | |
"net/http" | |
"os" | |
"os/signal" | |
"syscall" | |
"time" | |
"github.com/go-chi/chi/v5" | |
"github.com/go-chi/chi/v5/middleware" | |
"github.com/davecgh/go-spew/spew" | |
) | |
func main() { | |
log.SetFlags(log.LstdFlags | log.LUTC | log.Lmsgprefix | log.Lshortfile) | |
log.SetPrefix("[default]") | |
logger := log.New(log.Writer(), "[main]", log.Flags()) | |
router := chi.NewRouter() | |
router.Use( | |
middleware.Recoverer, | |
middleware.Logger) | |
router.Get("/", http.HandlerFunc(setcookie)) | |
h1 := http.NewServeMux() | |
h1.HandleFunc("/set", setcookie) | |
s1 := http.Server{ | |
Addr: ":8000", | |
Handler: h1, | |
} | |
h2 := http.NewServeMux() | |
h2.HandleFunc("/get", getcookie) | |
s2 := http.Server{ | |
Addr: ":9000", | |
Handler: h2, | |
} | |
go func() { | |
sigCh := make(chan os.Signal, 1) | |
signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT) | |
<-sigCh | |
logger.Println(s1.Shutdown(context.Background())) | |
logger.Println(s2.Shutdown(context.Background())) | |
}() | |
logger.Printf("server listening on [%s]\n", s1.Addr) | |
go s1.ListenAndServe() | |
s2.ListenAndServe() | |
} | |
func setcookie(rw http.ResponseWriter, _ *http.Request) { | |
http.SetCookie(rw, &http.Cookie{ | |
Name: "mycookie", | |
Value: "[email protected]", | |
Path: "/", | |
Domain: "localhost", | |
Expires: time.Now().UTC().Add(5 * time.Hour), | |
MaxAge: int(1000 * time.Second), | |
Secure: true, | |
HttpOnly: true, | |
SameSite: 1, | |
}) | |
} | |
func getcookie(rw http.ResponseWriter, r *http.Request) { | |
spew.Fdump(rw, r.Cookies()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment