Skip to content

Instantly share code, notes, and snippets.

@vitkarpov
Last active February 1, 2016 16:17
Show Gist options
  • Save vitkarpov/178d5713bab207de0333 to your computer and use it in GitHub Desktop.
Save vitkarpov/178d5713bab207de0333 to your computer and use it in GitHub Desktop.
Lorempixum HTTP API
package main
import (
"github.com/gorilla/mux"
"github.com/vitkarpov/lorempixum"
"log"
"net/http"
"os"
"strconv"
)
func main() {
// use mux wrapper instead of default golang http.handleFunc
// to get an ability defining params right inside the url
router := mux.NewRouter()
router.HandleFunc("/{format}/{width}/{height}", handlerImage)
http.Handle("/", router)
log.Fatal(http.ListenAndServe(":"+os.Getenv("PORT"), nil))
}
func handlerImage(res http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
width, err := strconv.Atoi(params["width"])
height, err := strconv.Atoi(params["height"])
size := width * height
// if user specified wrong params for request
// or size is too big (it's a question what is the limit, so let it be just 1000x1000)
if err != nil || size <= 0 || size > 1000000 {
res.WriteHeader(http.StatusBadRequest)
return
}
img := lorempixum.GetImage(width, height)
lorempixum.StreamImage(res, img, params["format"])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment