create a http server and parse cookies and return a json response in go

Here's an example code snippet to create an HTTP server in Go and parse cookies to return a JSON response:

main.go
package main

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

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // Parse cookies
        cookie, err := r.Cookie("myCookie")
        if err != nil {
            http.Error(w, err.Error(), http.StatusBadRequest)
            return
        }
        fmt.Printf("Cookie Value: %v\n", cookie.Value)

        // Set JSON response headers
        w.Header().Set("Content-Type", "application/json")

        // Define the JSON response
        jsonResponse := struct {
            Message string `json:"message"`
        }{
            Message: "Hello World!",
        }

        // Marshal JSON response
        jsonData, err := json.Marshal(jsonResponse)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }

        // Write JSON response to the HTTP response writer
        w.Write(jsonData)
    })

    log.Fatal(http.ListenAndServe(":8080", nil))
}

1031 chars
44 lines

To run this code, save it in a file called main.go, open a terminal session in the same directory and run go run main.go. This will start the HTTP server on http://localhost:8080.

related categories

gistlibby LogSnag