-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathurl-lib.rkt
54 lines (41 loc) · 1.77 KB
/
url-lib.rkt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; CourseGrid:url-lib.rkt ;;
;; ;;
;; Purpose: Wrapper for url library that caches results. ;;
;; Cached results prevent spamming site during development. ;;
;; ;;
;; Author: Willie Boag [email protected] ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#lang racket
(require net/url)
(provide url->port)
(provide read-url)
; Remove a set of characters from a target string
(define (remove-chars str to-remove)
(let
((dont-include (string->list to-remove)))
(list->string (map (lambda (c) (if (memq c dont-include)
#\_
c))
(string->list str)))))
; convert a url string to a filename to save to disk
(define (url->cache-entry s)
(string-append "url_cache/"
(string-trim (remove-chars s "/\\~:")
"_")))
; get the HTML data from a given URL
(define (url->port s)
(let
((filename (url->cache-entry s)))
; does file already exist in cache?
(cond
((not (file-exists? (string->path filename)))
(let
((html-data (port->bytes (get-pure-port (string->url s)
#:redirections 5))))
; Save data to cache
(display-to-file html-data filename))))
; get from local cache
(open-input-file filename)))
(define (read-url s)
(port->string (url->port s)))