create a http server with a options route in go

To create a http server with a route that handles the HTTP OPTIONS method in Go, you can use the built-in http package:

main.go
package main

import (
    "fmt"
    "net/http"
)

func handleOptions(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Allow", "GET, POST, OPTIONS");
    w.WriteHeader(http.StatusOK)
}

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, "Hello, World!")
    })

    http.HandleFunc("/options", handleOptions)

    http.ListenAndServe(":8080", nil)
}
420 chars
22 lines

In this example, we define a handler function handleOptions that sets the Allow header to the HTTP methods that are allowed on the /options route (GET, POST, and OPTIONS), and writes an HTTP status code of 200 (OK) to the response.

We then register this handler function using the http.HandleFunc function, and bind it to the /options route.

Finally, we start the HTTP server listening on port 8080 using the http.ListenAndServe function.

related categories

gistlibby LogSnag