Skip to content
Main.hs 1.08 KiB
Newer Older
Yuanle Song's avatar
Yuanle Song committed
{-# LANGUAGE OverloadedStrings #-}

import Control.Applicative ((<|>), liftA2)
import Data.Monoid ((<>))
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as L
import Web.Scotty

getClientIP1 :: ActionM (Maybe Text)
getClientIP1 = header "CLIENT-IP"
Yuanle Song's avatar
Yuanle Song committed

getClientIP2 :: ActionM (Maybe Text)
getClientIP2 =
  fmap (maybe Nothing (Just . firstElement)) (header "X-FORWARDED-FOR") where
Yuanle Song's avatar
Yuanle Song committed
      firstElement :: Text -> Text
      firstElement = head . L.splitOn ","

getClientIP3 :: ActionM (Maybe Text)
getClientIP3 = foldl1 (liftA2 (<|>)) $ map header ["X-FORWARDED"
                                                  ,"X-CLUSTER-CLIENT-IP"
                                                  ,"FORWARDED-FOR"
                                                  ,"FORWARDED"
                                                  ,"REMOTE-ADDR"]
Yuanle Song's avatar
Yuanle Song committed

getClientIP :: ActionM ()
getClientIP = do
  ip <- foldl1 (liftA2 (<|>)) [getClientIP1, getClientIP2, getClientIP3]
  case ip of
    Nothing -> text "unknown\n"
    Just rawIp -> text $ rawIp <> "\n"

main :: IO ()
main = scotty 3000 $ do
  get "/" $ getClientIP