With Go (golang) how to handle urls in the format / id / 123 not? Foo = bar

I am trying to parse a url like:

http://example.com/id/123

I read the net/url docs, but it seems like it only parses strings like

http://example.com/blah?id=123

How can I parse the identifier to get the id value in the first example? Thank you

I should have been more precise

This is not one of my own routes, but the http string returned by openid request

+4
source share
3 answers

In your example, / id / 123 has a path, and you can get the "123" part using Base from the path module.

 package main import ( "fmt" "path" ) func main() { fmt.Println(path.Base("/id/123")) } 

For convenience, read the documents on the path module here. http://golang.org/pkg/path/#example_Base

+6
source

You can try using regex as follows:

 import "regexp" re, _ := regexp.Compile("/id/(.*)") values := re.FindStringSubmatch(path) if len(values) > 0 { fmt.Println("ID : ", values[1]) } 
+5
source

Here is a simple solution that works for URLs with the same structure as yours (you can improve to fit those with other structures)

 package main import ( "fmt" "net/url" ) var path = "http://localhost:8080/id/123" func getFirstParam(path string) (ps string) { // ignore first '/' and when it hits the second '/' // get whatever is after it as a parameter for i := 1; i < len(path); i++ { if path[i] == '/' { ps = path[i+1:] } } return } func main() { u, _ := url.Parse(path) fmt.Println(u.Path) // -> "/id/123" fmt.Println(getFirstParam(u.Path)) // -> "123" } 

Or, as @gollipher suggested, use the path package

 import "path" func main() { u, _ := url.Parse(path) ps := path.Base(u.Path) } 

With this method, it is faster than a regular expression if you know the structure of the URL that you receive.

+1
source

All Articles