on develop help sign in
68 lines 2.5 kB history raw
1{-# LANGUAGE FlexibleContexts #-}
2{-# LANGUAGE OverloadedStrings #-}
3{-# LANGUAGE ScopedTypeVariables #-}
5-- |
6-- Module : Example.Storage
7-- Copyright : (c) 2015-2016 Brendan Hay
8-- License : Mozilla Public License, v. 2.0.
9-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
10-- Stability : provisional
11-- Portability : non-portable (GHC extensions)
12--
13module Example.Storage where
15import Control.Lens ((&), (.~), (<&>), (?~))
16import Control.Monad.Trans.Resource (liftResourceT, runResourceT)
18import Data.Conduit (runConduit, (.|))
19import Data.Text (Text)
21import System.IO (stdout)
23import qualified Data.Conduit.Binary as Conduit
24import qualified Data.Text as Text
25import qualified Network.Google as Google
26import qualified Network.Google.Storage as Storage
29-- This will calculate the MIME type (and therefore Content-Type) of
30-- the stored object based on the file extension.
31--
32-- You can explicitly set the desired MIME type by using:
33-- {-
34-- import Network.HTTP.Media ((//))
35----
36-- b <- sourceBody f <&> bodyContentType .~ "application" // "json"
37-- ...
38--
39-- -}
40--example :: Text -> FilePath -> IO ()
41example bucket input output = do
42 -- Setup a logger to emit 'Debug' (or higher) log statements to 'stdout':
43 lgr <- Google.newLogger Google.Debug stdout
45 -- Create a new environment which will discover the appropriate
46 -- AuthN/AuthZ credentials, and explicitly state the OAuth scopes
47 -- we will be using below, which will be enforced by the compiler:
48 env <- Google.newEnv <&>
49 (Google.envLogger .~ lgr)
50 . (Google.envScopes .~ Storage.storageReadWriteScope)
52 -- Create a streaming 'Conduit' source of the input file contents:
53 body <- Google.sourceBody input
55 let key = Text.pack input
57 runResourceT . Google.runGoogle env $ do
58 -- Upload the 'input' file contents to the specified bucket, using
59 -- the file path as the key:
60 _ <- Google.upload (Storage.objectsInsert bucket Storage.object' & Storage.oiName ?~ key) body
62 -- Download from the bucket/key and create a source of the HTTP stream:
63 stream <- Google.download (Storage.objectsGet bucket key)
65 -- 'Conduit' actions such as '.|' need to be lifted into the 'Google'
66 -- monad using 'liftResourceT', this will stream the received bytes
67 -- into the 'output' file:
68 liftResourceT (runConduit (stream .| Conduit.sinkFile output))