Saturday 4 September 2021

Go URL Parsing

 Go has good support for url parsing. URL contains a scheme, authentication info, host, port, path, query params, and query fragment. we can parse URL and deduce what are the parameter is coming to the server and then process the request accordingly.

The net/url package has the required functions like Scheme, User, Host, Path, RawQuery etc.

Go URL Parsing Example 1

  1. package main  
  2. import "fmt"  
  3. import "net"  
  4. import "net/url"  
  5. func main() {  
  6.   
  7.     p := fmt.Println  
  8.   
  9.     s := "Mysql://admin:password@serverhost.com:8081/server/page1?key=value&key2=value2#X"  
  10.   
  11.     u, err := url.Parse(s)  
  12.     if err != nil {  
  13.         panic(err)  
  14.     }  
  15.     p(u.Scheme) //prints Schema of the URL  
  16.     p(u.User)   // prints the parsed user and password  
  17.     p(u.User.Username())    //prints user's name  
  18.     pass, _ := u.User.Password()  
  19.     p(pass)     //prints user password  
  20.     p(u.Host)       //prints host and port  
  21.     host, port, _ := net.SplitHostPort(u.Host)       //splits host name and port  
  22.     p(host)     //prints host  
  23.     p(port)     //prints port  
  24.     p(u.Path)       //prints the path  
  25.     p(u.Fragment)       //prints fragment path value  
  26.     p(u.RawQuery)       //prints query param name and value as provided  
  27.     m, _ := url.ParseQuery(u.RawQuery)      //parse query param into map  
  28.     p(m)        //prints param map  
  29.     p(m["key2"][0])     //prints specific key value  
  30. }  

Output:

mysql
admin:password
admin
password
serverhost.com:8081
serverhost.com
8081
/server/page1
X
key=value&key2=value2
map[key:[value] key2:[value2]]
value2 

Go URL Parsing Example 2

  1. package main  
  2.   
  3. import (  
  4.     "io"  
  5.     "net/http"  
  6. )  
  7.   
  8.   
  9. func main() {  
  10.     http.HandleFunc("/company", func(res http.ResponseWriter, req *http.Request) {  
  11.         displayParameter(res, req)  
  12.     })  
  13.     println("Enter the url in browser:  http://localhost:8080/company?name=Tom&age=27")  
  14.     http.ListenAndServe(":8080", nil)  
  15. }  
  16. func displayParameter(res http.ResponseWriter, req *http.Request) {  
  17.     io.WriteString(res, "name: "+req.FormValue("name"))  
  18.     io.WriteString(res, "\nage: "+req.FormValue("age"))  
  19. }  

Output:

Enter the url in browser: http://localhost:8080/company?name=Tom&age=27

Go Url Passing 1








No comments:

Post a Comment