- Go Programming Blueprints(Second Edition)
- Mat Ryer
- 524字
- 2021-07-08 10:40:02
Endpoints with dynamic paths
Pattern matching for the http
package in the Go standard library isn't the most comprehensive and fully featured implementation out there. For example, Ruby on Rails makes it much easier to have dynamic segments inside the path. You could map the route like this:
"auth/:action/:provider_name"
Rails then provides a data map (or dictionary) containing the values that it automatically extracted from the matched path. So if you visit auth/login/google
, then params[:provider_name]
would equal google
and params[:action]
would equal login
.
The most the http
package lets us specify by default is a path prefix, which we can make use of by leaving a trailing slash at the end of the pattern:
"auth/"
We would then have to manually parse the remaining segments to extract the appropriate data. This is acceptable for relatively simple cases. This suits our needs for the time being since we only need to handle a few different paths, such as the following:
/auth/login/google
/auth/login/facebook
/auth/callback/google
/auth/callback/facebook
Tip
If you need to handle more advanced routing situations, you may want to consider using dedicated packages, such as goweb
, pat
, routes
, or mux
. For extremely simple cases such as ours, built-in capabilities will do.
We are going to create a new handler that powers our login process. In auth.go
, add the following loginHandler
code:
// loginHandler handles the third-party login process. // format: /auth/{action}/{provider} func loginHandler(w http.ResponseWriter, r *http.Request) { segs := strings.Split(r.URL.Path, "/") action := segs[2] provider := segs[3] switch action { case "login": log.Println("TODO handle login for", provider) default: w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "Auth action %s not supported", action) } }
In the preceding code, we break the path into segments using strings.Split
before pulling out the values for action
and provider
. If the action value is known, we will run the specific code; otherwise, we will write out an error message and return an http.StatusNotFound
status code (which in the language of HTTP status code is 404
).
Note
We will not bulletproof our code right now. But it's worth noticing that if someone hits loginHandler
with few segments, our code will panic because it would expect segs[2]
and segs[3]
to exist.
For extra credit, see whether you can protect your code against this and return a nice error message instead of making it panic if someone hits /auth/nonsense
.
Our loginHandler
is only a function and not an object that implements the http.Handler
interface. This is because, unlike other handlers, we don't need it to store any state. The Go standard library supports this, so we can use the http.HandleFunc
function to map it in a way similar to how we used http.Handle
earlier. In main.go
, update the handlers:
http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"})) http.Handle("/login", &templateHandler{filename: "login.html"}) http.HandleFunc("/auth/", loginHandler) http.Handle("/room", r)
Rebuild and run the chat application:
go build -o chat ./chat -host=":8080"
Hit the following URLs and notice the output logged in the terminal:
http://localhost:8080/auth/login/google
outputsTODO handle login for google
http://localhost:8080/auth/login/facebook
outputsTODO handle login for facebook
We have successfully implemented a dynamic path-matching mechanism that just prints out TODO
messages so far; we need to integrate it with authorization services in order to make our login process work.
- Learning Python Web Penetration Testing
- 零基礎學Visual C++第3版
- HoloLens Beginner's Guide
- 實用防銹油配方與制備200例
- Java Web應用開發技術與案例教程(第2版)
- Jenkins Continuous Integration Cookbook(Second Edition)
- Node.js Design Patterns
- 精通Python自動化編程
- Unity&VR游戲美術設計實戰
- Serverless Web Applications with React and Firebase
- Distributed Computing in Java 9
- 算法圖解
- Mastering Embedded Linux Programming
- C# 7.0本質論
- AngularJS UI Development