Last active
February 1, 2016 16:17
-
-
Save vitkarpov/178d5713bab207de0333 to your computer and use it in GitHub Desktop.
Lorempixum HTTP API
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
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