create a http server and parse cookies in go

Here's an example of how to create an HTTP server in Go and parse cookies:

main.go
package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", handleRequest)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
    // Parse cookies
    cookies := r.Cookies()

    // Iterate over cookies
    for _, cookie := range cookies {
        fmt.Fprintf(w, "Cookie: %s=%s\n", cookie.Name, cookie.Value)
    }

    fmt.Fprintf(w, "Hello, World!")
}
456 chars
25 lines

In this example, we create an HTTP server and set the handler function to handleRequest. In handleRequest, we use http.Request to parse cookies via the Cookies() method. We then iterate over the cookies and print each one's name and value using http.ResponseWriter. Finally, we print "Hello, World!".

Note that for testing cookie parsing, you can pass a cookie to the server using the -H flag in curl:

main.go
curl -H "Cookie: key=value" http://localhost:8080/
51 chars
2 lines

This will pass a cookie with the name "key" and the value "value" to the server.

related categories

gistlibby LogSnag