計算機科学のブログ

実践Haskell HaskellでのHTTPリクエストの作成 失敗、メッセージの取得、getResponseStatus関数

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT7(実践Haskell)、LESSON 39(HaskellでのHTTPリクエストの作成)、39.6(練習問題)Q39-2の解答を求めてみる。

コード

app/Main.hs

{-# LANGUAGE OverloadedStrings #-}
module Main where

import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as LC
import Network.HTTP.Simple

import Lib

myToken :: BC.ByteString
myToken = "<API トークン>"

noaaHost :: BC.ByteString
noaaHost = "www.ncdc.noaa.gov"

apiPath :: BC.ByteString
apiPath = "/cdo-Web/api/v2/datasets"

buildRequest :: BC.ByteString -> BC.ByteString -> BC.ByteString
 -> BC.ByteString -> Request
buildRequest token host method path =
    setRequestMethod method
    $ setRequestHost host
    $ setRequestHeader "token" [myToken]
    $ setRequestPath path
    $ setRequestSecure True
    $ setRequestPort 443
    $ defaultRequest

request :: Request
request = buildRequest myToken noaaHost "GET" apiPath

main :: IO ()
main = do
    response <- httpLBS request
    let status = getResponseStatusCode response
    putStrLn $ if status == 200
               then "成功"
               else show $ getResponseStatus response

入出力結果(Terminal, Zsh)

% stack build && stack exec http-lesson-exe
http-lesson> build (lib + exe)
Preprocessing library for http-lesson-0.1.0.0..
Building library for http-lesson-0.1.0.0..
Preprocessing executable 'http-lesson-exe' for http-lesson-0.1.0.0..
Building executable 'http-lesson-exe' for http-lesson-0.1.0.0..
[2 of 2] Compiling Main
Linking .stack-work/dist/x86_64-osx/Cabal-3.2.1.0/build/http-lesson-exe/http-lesson-exe ...
http-lesson> copy/register
Installing library in /Users/kamimura/…/http-lesson/.stack-work/install/x86_64-osx/da17063b65a7a783c62606a59d4c8648662590f1aae947bb9b44f55ebde3c3ce/8.10.7/lib/x86_64-osx-ghc-8.10.7/http-lesson-0.1.0.0-4HjsXjWMuGD4Qdl4b71maU
Installing executable http-lesson-exe in /Users/kamimura/…/http-lesson/.stack-work/install/x86_64-osx/da17063b65a7a783c62606a59d4c8648662590f1aae947bb9b44f55ebde3c3ce/8.10.7/bin
Registering library for http-lesson-0.1.0.0..
Status {statusCode = 404, statusMessage = "Not Found"}
%