url parse


Node.js

  1. const url = require('url')
  2. const qs = require('querystring')
  3. const urlstr = 'http://bob:secret@sub.example.com:8080/somepath?foo=bar'
  4. const parsed = url.parse(urlstr)
  5. console.log(parsed.protocol)
  6. console.log(parsed.auth)
  7. console.log(parsed.port)
  8. console.log(parsed.hostname)
  9. console.log(parsed.pathname)
  10. console.log(qs.parse(parsed.search.substr(1)))

Output

  1. http:
  2. bob:secret
  3. 8080
  4. sub.example.com
  5. /somepath
  6. { foo: 'bar' }

Go

  1. package main
  2. import (
  3. "fmt"
  4. "net/url"
  5. )
  6. func main() {
  7. urlstr := "http://bob:secret@sub.example.com:8080/somepath?foo=bar"
  8. u, err := url.Parse(urlstr)
  9. if err != nil {
  10. panic(err)
  11. }
  12. fmt.Println(u.Scheme)
  13. fmt.Println(u.User)
  14. fmt.Println(u.Port())
  15. fmt.Println(u.Hostname())
  16. fmt.Println(u.Path)
  17. fmt.Println(u.Query())
  18. }

Output

  1. http
  2. bob:secret
  3. 8080
  4. sub.example.com
  5. /somepath
  6. map[foo:[bar]]