- Hands-On RESTful Web Services with Go
- Naren Yellavula
- 427字
- 2021-06-24 17:04:25
Developing a UUID generation API using ServeMux
A UUID is a unique identifier for a resource or a transaction. UUIDs are widely used for identifying an HTTP request. Let us develop an API for generating a UUID. Please follow these steps:
- Create the program file as follows:
touch -p $GOPATH/src/github.com/git-user/chapter2/uuidGenerator/main.go
- Any Go struct with a few dedicated HTTP methods is qualified to be a ServeMux. For example, we can create a custom UUID struct and implement the ServeHTTP function in order to make it a ServeMux object. Following is the implementation for the uuidGenerator.go module:
import (
"crypto/rand"
"fmt"
)
// UUID is a custom multiplexer
type UUID struct {
}
func (p *UUID) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
giveRandomUUID(w, r)
return
}
http.NotFound(w, r)
return
}
func giveRandomUUID(w http.ResponseWriter, r *http.Request) {
c := 10
b := make([]byte, c)
_, err := rand.Read(b)
if err != nil {
panic(err)
}
fmt.Fprintf(w, fmt.Sprintf("%x", b))
}
It consists of the UUID struct that acts as a ServeMux object. We can access the URL path in the handler function and use that information to manually route the requests to different response generators.
giveRandomUUID is a response generator function that sets a random UUID string to response. Go's crypto package has a Read function that fills random characters into a byte array.
- Now add a main function to the module using the ServeMux object. We should pass our ServeMux to the http.ListenAndServe function to get our content served. We are serving our content on port 8000:
package main
import (
"net/http"
)
func main() {
mux := &UUID{}
http.ListenAndServe(":8000", mux)
}
We use UUID as a multiplexer in the ListenAndServe function, which starts an HTTP server. The server executes the ServeHTTP method that is defined preceding on the mux object.
- Run the following command from your shell/Terminal:
go run $GOPATH/src/github.com/git-user/chapter2/uuidGenerator/main.go
- We can make a curl request like this to make a request to the web server that is listening on port 8000:
curl -X GET http://localhost:8000/
The response that is returned will be a random string:
544f5519592ac25bb2c0
Until now, we have worked with a single handler. Let us see how we can add multiple handlers to route to different function handlers using ServeMux.
- 黑客攻防從入門到精通(實(shí)戰(zhàn)秘笈版)
- Unity 2020 By Example
- JavaScript+jQuery網(wǎng)頁特效設(shè)計(jì)任務(wù)驅(qū)動(dòng)教程(第2版)
- JavaScript語言精髓與編程實(shí)踐(第3版)
- Python數(shù)據(jù)分析(第2版)
- Python面向?qū)ο缶幊蹋簶?gòu)建游戲和GUI
- Mastering Unity 2D Game Development(Second Edition)
- Android傳感器開發(fā)與智能設(shè)備案例實(shí)戰(zhàn)
- 零基礎(chǔ)學(xué)HTML+CSS
- Arduino機(jī)器人系統(tǒng)設(shè)計(jì)及開發(fā)
- JavaScript Concurrency
- 一覽眾山小:ASP.NET Web開發(fā)修行實(shí)錄
- Java面試一戰(zhàn)到底(基礎(chǔ)卷)
- 虛擬現(xiàn)實(shí):引領(lǐng)未來的人機(jī)交互革命
- 打造流暢的Android App