Last active
August 29, 2015 14:03
-
-
Save danhyun/ec99ad7916ec6b152e79 to your computer and use it in GitHub Desktop.
A groovy service that validates HTML fragments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For use with your own local copy of nu validator @ http://about.validator.nu/#src | |
@GrabConfig(systemClassLoader=true) | |
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7') | |
import groovyx.net.http.HTTPBuilder | |
def client = new HTTPBuilder('http://localhost:8888') | |
def boundary = '----hyunlabs_boundary' | |
def separator = "--${boundary}" | |
def end = "--${boundary}--" | |
client.setHeaders('Content-Type': "multipart/form-data; boundary=${boundary}") | |
def validStringResponse = "The document validates according to the specified schema(s) and to additional constraints checked by the validator." | |
def requestBody = { String body -> | |
"""${separator} | |
Content-Disposition: form-data; name="parser" | |
text/html | |
${separator} | |
Content-Disposition: form-data; name="out" | |
text | |
${separator} | |
Content-Disposition: form-data; name="level" | |
error | |
${separator} | |
Content-Disposition: form-data; name="content" | |
<!DOCTYPE html><html><head><title>1</title></head><body>${body}</body></html> | |
${end} | |
""".split("\n").join("\r\n") | |
} | |
def isValid = { String body -> | |
!body || !body.trim() || validStringResponse == client.post(body: requestBody(body))?.text?.trim() | |
} | |
assert !isValid('<p </a>') | |
assert isValid() | |
assert isValid(null) | |
assert isValid("") | |
assert isValid(" ") | |
assert isValid("\t") | |
assert isValid("<p> hi</p>") | |
assert isValid("helo world") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment