Skip to content

Instantly share code, notes, and snippets.

@radu-matei
Created April 1, 2023 22:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radu-matei/459490d01e7231532c5e4daeec55c99f to your computer and use it in GitHub Desktop.
Save radu-matei/459490d01e7231532c5e4daeec55c99f to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net/http"
spinhttp "github.com/fermyon/spin/sdk/go/http"
)
func init() {
spinhttp.Handle(func(w http.ResponseWriter, r *http.Request) {
router := spinhttp.NewRouter()
router.GET("/hello/:name", Hello)
router.GET("/this/will/*catchAll", CatchAll)
router.GET("/supersecret", BasicAuth(SuperSecret, "user", "pass"))
router.ServeHTTP(w, r)
})
}
func Hello(w http.ResponseWriter, _ *http.Request, ps spinhttp.Params) {
fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}
func CatchAll(w http.ResponseWriter, _ *http.Request, ps spinhttp.Params) {
fmt.Fprintf(w, "catch all: %s!\n", ps.ByName("catchAll"))
}
func SuperSecret(w http.ResponseWriter, _ *http.Request, _ spinhttp.Params) {
fmt.Fprintf(w, "This is super secret and behind auth!\n")
}
func BasicAuth(h spinhttp.RouterHandle, requiredUser, requiredPassword string) spinhttp.RouterHandle {
return func(w http.ResponseWriter, r *http.Request, ps spinhttp.Params) {
// Get the Basic Authentication credentials
user, password, hasAuth := r.BasicAuth()
if hasAuth && user == requiredUser && password == requiredPassword {
// Delegate request to the given handle
h(w, r, ps)
} else {
// Request Basic Authentication otherwise
w.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
}
}
}
func main() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment