Last active
April 21, 2017 22:41
-
-
Save excavador/55c0e7fec766956ecd7a9362e72e1369 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
package rest | |
import ( | |
"fmt" | |
"net/http" | |
"strings" | |
"unicode" | |
) | |
func RuneIsAscii(c rune) bool { | |
return c < unicode.MaxASCII | |
} | |
func FileNameIsAscii(filename string) bool { | |
for _, c := range filename { | |
if !RuneIsAscii(c) { | |
return false | |
} | |
} | |
return true | |
} | |
func RuneNeedEscape(c rune) bool { | |
if !RuneIsAscii(c) { | |
return false | |
} | |
if uint(c) < 0x20 { | |
return true | |
} | |
return c == ';' || c == '\n' || c == '"' || c == '\\' | |
} | |
func RuneEscape(c rune) rune { | |
if RuneNeedEscape(c) { | |
return '_' | |
} else { | |
return c | |
} | |
} | |
func FileNameEscape(filename string) string { | |
return strings.Map(RuneEscape, filename) | |
} | |
func ContentDispositionAttachment(header http.Header, filename string) { | |
filename = FileNameEscape(filename) | |
var value string | |
if FileNameIsAscii(filename) { | |
value = `attachment; filename=%s` | |
} else { | |
value = `attachment; filename*=UTF-8''%s` | |
} | |
header.Set("Content-Disposition", fmt.Sprintf(value, filename)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment