Skip to content

Instantly share code, notes, and snippets.

@samth
Created March 19, 2012 01:13
Show Gist options
  • Save samth/2088753 to your computer and use it in GitHub Desktop.
Save samth/2088753 to your computer and use it in GitHub Desktop.
Post images to imgur with Racket
#lang racket
(require net/url net/uri-codec net/base64 json)
(define f #f)
(command-line #:args (file)
(set! f file))
(define file-val (file->string f))
(define (fail . _)
(error 'gist "failed to post image"))
(define data
(string->bytes/utf-8
(format "{\"public\":true,\"files\": {\"~a\": {\"content\":\"~a\"}}}"
f (file->string f))))
;(displayln data)
(define js
(values #;bytes->jsexpr
(port->bytes
(post-impure-port
(string->url "https://api.github.com/gists")
(jsexpr->bytes
(hash 'public true
'files (hash (string->symbol f)
(hash 'content (file->string f)))))
empty))))
#;
(unless (hash? js) (fail))
(pretty-print js)
#lang racket
(require net/url net/uri-codec net/base64 json)
(define key "b13dfa3e4f30de11163e8a5a02036a8a")
(define f #f)
(command-line #:args (file)
(set! f file))
(define file-bytes (base64-encode (file->bytes f) #""))
(define (fail . _)
(error 'imgur "failed to post image"))
(define js
(with-handlers ([exn:fail? fail])
(bytes->jsexpr
(port->bytes
(post-pure-port
(string->url "https://api.imgur.com/2/upload.json")
(string->bytes/utf-8 (alist->form-urlencoded
`((key . ,key)
(image . ,(bytes->string/utf-8 file-bytes)))))
(list "Content-Type: application/x-www-form-urlencoded"))))))
(unless (hash? js) (fail))
(define links
(hash-ref
(hash-ref js 'upload fail)
'links))
(printf "Page URL: ~a\n" (hash-ref links 'imgur_page))
(printf "Image URL: ~a\n" (hash-ref links 'original))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment