golangの日記

Go言語を中心にプログラミングについてのブログ

はてなAPIを使ってブログエントリを投稿するときの編集モード

はてなAPIのドキュメント


はてなAPIは、ドキュメントがしっかり書かれているので、
困ることはないですが、ブログの編集モードに関して

  • text/html (見たままモード)
  • text/x-markdown (マークダウン記法)
  • text/x-hatena-syntax (はてな記法)


XML 内の content の type 属性に、以下のように text/x-markdown を指定すれば、
マークダウンモードにできると思ったんですが、投稿すると text/html になってました。

<content type="text/x-markdown">本文</content>

どうやら 「ブログの設定 -> 基本設定 -> 編集モード」 で選択したモードで決定されるようです。
なので、設定でマークダウンモードを選択すると content の type 属性が何であろうとマークダウンモードでアップされるみたいです。


以下、パッケージを使ったGo言語での OAuth GET サンプル

使用した Go言語の OAuth パッケージ

github.com/gomodule/oauth1/oauth


  • GETの例
import (
    "net/url"

    "github.com/gomodule/oauth1/oauth"
)

func main() {
    
    scope := url.Values{"scope": {"read_public", "write_public", "read_private", "write_private"}}

    oauthClient := &oauth.Client{
        Credentials: oauth.Credentials{
            Token:  "ConsumerKey",
            Secret: "ConsumerSecret",
        },
        TemporaryCredentialRequestURI: "https://www.hatena.com/oauth/initiate",
        ResourceOwnerAuthorizationURI: "https://www.hatena.com/oauth/authorize",
        TokenRequestURI:               "https://www.hatena.com/oauth/token",
    }

    credentials := &oauth.Credentials{
        Token:  "Token",
        Secret: "TokenSecret",
    }
    
    resp, err := oauthClient.Get(nil, credentials, "https://blog.hatena.ne.jp/{はてなID}/{ブログID}/atom", scope)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
    }
    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(body)
}


  • ヘッダーの設定のみ行う
import (
    "fmt"
    "net/http"
    "net/url"
    "os"
    "strings"
    "github.com/gomodule/oauth1/oauth"
)

func main() {

    scope := url.Values{"scope": {"read_public", "write_public", "read_private", "write_private"}}

    req, err := http.NewRequest("GET", "https://blog.hatena.ne.jp/{はてなID}/{ブログID}/atom", strings.NewReader(scope.Encode()))
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

    if err := oauthClient.SetAuthorizationHeader(req.Header, credentials, req.Method, req.URL, scope); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
    }
    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(body)
}