Created
April 1, 2023 22:53
-
-
Save radu-matei/459490d01e7231532c5e4daeec55c99f to your computer and use it in GitHub Desktop.
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 ( | |
"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