- Hands-On RESTful Web Services with Go
- Naren Yellavula
- 284字
- 2021-06-24 17:04:27
Path-based matching
A path parameter in the URL of an HTTP GET request looks like this:
https://example.org/articles/books/123
Since it is passed after the base URL and API endpoint, in this case https://example.org/articles/, they are called path parameters. In the preceding URL, books and 123 are path parameters. Let us see an example of how to create routes that can consume data supplied as path parameters. Follow these steps:
- Create a new file for our program at the following path:
touch -p $GOPATH/src/github.com/git-user/chapter2/muxRouter/main.go
- The idea is to create a new router, mux.NewRouter, and use it as a handler with in-built http.Server. We can attach URL endpoints to handler functions on this router object. The URL endpoints attached can also be regular expressions. The simple program to collect path parameters from a client HTTP request and return back the same looks like this:
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
)
func ArticleHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Category is: %v\n", vars["category"])
fmt.Fprintf(w, "ID is: %v\n", vars["id"])
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
srv := &http.Server{
Handler: r,
Addr: "127.0.0.1:8000",
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}
- Now run the server using the following command in a shell:
go run $GOPATH/src/github.com/git-user/chapter2/muxRouter/main.go
- Make a curl request from another shell and we can get the output as follows:
curl http://localhost:8000/articles/books/123
Category is: books ID is: 123
This example shows how to match and parse path parameters. There is one more popular way to collect variable information from an HTTP request and that is with query parameters. In the next section, we see how to create routes that match HTTP requests with query parameters.
推薦閱讀
- vSphere High Performance Cookbook
- 軟件工程
- 量化金融R語言高級教程
- Mastering Android Development with Kotlin
- Node Cookbook(Second Edition)
- TMS320LF240x芯片原理、設計及應用
- 一本書講透Java線程:原理與實踐
- Django 3.0應用開發詳解
- 后臺開發:核心技術與應用實踐
- Oracle 12c從入門到精通(視頻教學超值版)
- Clojure Web Development Essentials
- jQuery Mobile Web Development Essentials(Second Edition)
- WCF全面解析
- C語言編程魔法書:基于C11標準
- Office VBA開發經典:中級進階卷