Created
May 25, 2015 21:33
-
-
Save mettledrum/929bcd250d0bfda2310e to your computer and use it in GitHub Desktop.
use suffix to PDF-ify any ol' endpoint
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 main | |
import ( | |
"fmt" | |
"log" | |
"net/http" | |
"github.com/gorilla/context" | |
"github.com/gorilla/mux" | |
"github.com/terryh/gopdf" | |
) | |
func main() { | |
r := mux.NewRouter() | |
// TODO: use valid path characters regex: /^([!#$&-;=?-[]_a-z~]|%[0-9a-fA-F]{2})+$/ | |
r.HandleFunc("/{inner_url:[0-9/A-Za-z._]+}/to_pdf", PDFHandle).Methods("GET") | |
r.HandleFunc("/serve/me/plz", SomeHandler).Methods("GET") | |
http.Handle("/", r) | |
log.Println("listening on 0.0.0.0:8080") | |
err := http.ListenAndServe(":8080", context.ClearHandler(http.DefaultServeMux)) | |
log.Println(err) | |
} | |
func SomeHandler(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, "<div> ¡Hi Mom! </div>") | |
} | |
func PDFHandle(w http.ResponseWriter, r *http.Request) { | |
// get URL string before "/to_pdf" | |
u := r.URL.String() | |
u = u[:len(u)-(len("/to_pdf"))] | |
p := "http://" + r.Host + u | |
log.Println("going to PDF-ify: ", p) | |
result, err := gopdf.Url2pdf(p) | |
log.Println(err) | |
w.Header().Set("Content-Type", "application/pdf") | |
w.Write(result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment