Reproduced
Go basic Learning Record-write Web application-Secure authentication
Security verification
There are a number of features in front of it, but the program has a serious security vulnerability that allows users to access any path read/write on the server.
To alleviate this situation, we can write a function to validate the caption with a regular expression.
First, add "RegExp" to the import list.
Then we can create a global variable to store our validation expression:
var validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$")
function RegExp. Mustcompile will parse and compile the regular expression and return a regexp. Regexp.
The difference between mustcompile and compile is that if an expression fails to compile, it will have an exception, and compile will return the error as the second parameter.
Now, let's write a function that uses the Validpath expression to validate the path and extract the page title
func getTitle(w http.ResponseWriter, r *http.Request) (string, error) { m := validPath.FindStringSubmatch(r.URL.Path) if m == nil { http.NotFound(w, r) return "", errors.New("无效的页面标题") } return m[2], nil // 标题是第二个子表达式中}
If the title is valid, it is returned with the nil error value.
If the caption is not valid, the function writes a "404 Not Found" error to the HTTP connection and returns an error to the handler.
To create a new error, we must import the error package.
The following calls the GetTitle in each handler:
func viewhandler (w http. Responsewriter, R *http. Request) {title, Err: = GetTitle (W, R) if Err! = nil {return} p, err: = LoadPage (title) If Err! = Nil {http. Redirect (W, R, "/edit/" +title, http. Statusfound) return} rendertemplate (W, "View", p)}func Edithandler (w http. Responsewriter, R *http. Request) {title, Err: = GetTitle (W, R) if Err! = nil {return} p, err: = LoadPage (title) If Err! = Nil {p = &page{title:title}} rendertemplate (W, "edit", p)}func Savehandler (w http). Responsewriter, R *http. Request) {title, Err: = GetTitle (W, R) if Err! = nil {return} body: = R.formvalue ("Body") P: = &A mp page{Title:title, Body: []byte (Body),} err = P.save () if err! = Nil {http. Error (W, err. Error (), HTTP. Statusinternalservererror)} http. Redirect (W, R, "/view/" +title, http. Statusfound)}
After the modification, recompile and run the program, when accessing non-edit, view, save route, an exception error message appears