Mapping URL Parameters in Native Go
Can native Go handle inline URL parameters? Consider the URL http://localhost:8080/blob/123/test, which we aim to map to /blob/{id}/test. This question explores Go's native capabilities for such mappings without relying on external libraries.
Native Approach:
Native Go does not offer a straightforward mechanism for this task. However, implementing it manually is relatively simple.
The following function, getCode(), parses the request URL and extracts the code from the first part of the path:
func getCode(r *http.Request, defaultCode int) (int, string) { p := strings.Split(r.URL.Path, "/") if len(p) == 1 { return defaultCode, p[0] } else if len(p) > 1 { code, err := strconv.Atoi(p[0]) if err == nil { return code, p[1] } else { return defaultCode, p[1] } } else { return defaultCode, "" } }
This function provides a basic way to map URL parameters in native Go, enabling you to interact with URLs like /blob/{id}/test effectively.
The above is the detailed content of Can Native Go Handle URL Parameters?. For more information, please follow other related articles on the PHP Chinese website!