No F*cking Idea

Common answer to everything

Working With URL Quick Tip Network.Url

| Comments

I have bigger text to post but before i will do it i have to split it into smaller parts so it will not be one long post about everything.

cat explaining stuff

Working with URL’s

Most of the time when preparing to make an http request in haskell eg. using simpleHTTP we need to build a request. We have several ways to do it, one of them would be to ugly glue strings together but thats not the way to do it in a safe way. Happily for us we have url, (cabal install url) package that adds Network.Url package. And here i will show few quick tips how to use it to work with urls.

Step one: Import

First thing we have to do is to import our package :D and string into our url lib.

start.hs
1
2
3
4
5
6
7
8
9
10
import Network.URL

main = do
  putStrLn "give me some url:"
  rawUrl <- getLine
  let maybeUrl = importURL rawUrl in
    case maybeUrl of
    Just url ->
      putStrLn $ exportURL $ add_param url ("param_name","param_value")
    Nothing  -> putStrLn "Sorry but this doesn't look like url"

This is the super simple example. But how it work? First of all we have importURL with signature:

1
importURL :: String -> Maybe URL

This will import url in form of string to url library and give us back Maybe URL. This is awesome! So we will have type that we can work on Yay! To exit library and get back string. We need to use exportURL with signature:

1
exportURL :: URL -> String

So we are only doing some simple transformation String ~>~ Maybe URL ~>~ URL ~>~ String thats nothing we can’t handle!

Next important bit is add_param function with signature:

1
add_param :: URL -> (String, String) -> URL

This does exactly what we would expect :D If we need to add to url http://google.com two params ok=1 and query=haskell To build http://google.com?query=haskell&ok=1.

Step two: More detailed example

I will try to reiterate our first example showing a bit more thing. Or just same things in a different way. Lets try to add two params.

ue2.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import Network.URL

prepareUrl url =
  let newUrl = add_param url ("query","gimme cats pics") in
    add_param newUrl ("size", "any")

main = do
  putStrLn "give me some url:"
  rawUrl <- getLine
  let maybeUrl = importURL rawUrl in
    case maybeUrl of
    Just url ->
      putStrLn $ exportURL $ prepareUrl url
    Nothing  -> putStrLn "Sorry but this doesn't look like url"

You should run the code and see something like this:

ue2.hs
1
2
3
4
 λ ./ue2
give me some url:
lambdacu.be
lambdacu.be?size=any&query=gimme+cats+pics

Summary

It is just a quick tip :) Network.URL has few more functions eg. to check if protocol is secure and checking if params are ok. But stuff showed above is the main point of lib.

More about this lib ofc on hackage: http://hackage.haskell.org/package/url-2.1/docs/Network-URL.html

….And quick tip should be quick :)

Comments