- 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.
- 手機安全和可信應(yīng)用開發(fā)指南:TrustZone與OP-TEE技術(shù)詳解
- 新一代通用視頻編碼H.266/VVC:原理、標準與實現(xiàn)
- Vue.js前端開發(fā)基礎(chǔ)與項目實戰(zhàn)
- Vue.js 3.x從入門到精通(視頻教學(xué)版)
- Java面向?qū)ο蟪绦蜷_發(fā)及實戰(zhàn)
- Data Analysis with Stata
- Spring Boot企業(yè)級項目開發(fā)實戰(zhàn)
- Getting Started with Gulp
- 西門子S7-200 SMART PLC編程從入門到實踐
- Python High Performance Programming
- 大話Java:程序設(shè)計從入門到精通
- Learning Ionic
- Flask Web開發(fā):基于Python的Web應(yīng)用開發(fā)實戰(zhàn)(第2版)
- Android系統(tǒng)下Java編程詳解
- ASP.NET jQuery Cookbook(Second Edition)