Skip to content

Instantly share code, notes, and snippets.

@sugyan
Last active November 11, 2017 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sugyan/e9c73ac1c11a577fa9df55957b1f2b0c to your computer and use it in GitHub Desktop.
Save sugyan/e9c73ac1c11a577fa9df55957b1f2b0c to your computer and use it in GitHub Desktop.
package app
import (
"bytes"
"image/gif"
"image/jpeg"
"image/png"
"net/http"
"path"
"strings"
"github.com/sugyan/shogi/format/csa"
"github.com/sugyan/shogi/util/image"
"google.golang.org/appengine"
"google.golang.org/appengine/log"
)
func init() {
http.Handle("/", http.StripPrefix("/", http.HandlerFunc(handler)))
}
func handler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "favicon.ico" {
http.NotFound(w, r)
return
}
ctx := appengine.NewContext(r)
b := bytes.NewBuffer([]byte{})
for _, l := range strings.Split(r.URL.Path, "/") {
if strings.HasPrefix(l, "P") {
b.WriteString(l + "\n")
}
}
state, err := csa.Parse(b)
if err != nil {
log.Errorf(ctx, "failed to parse: %s", err.Error())
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
var options *image.StyleOptions
if strings.HasPrefix(path.Base(r.URL.Path), "simple") {
options = &image.StyleOptions{
Board: image.BoardStripe,
Piece: image.PieceDirty,
}
}
if strings.HasPrefix(path.Base(r.URL.Path), "random") {
options = &image.StyleOptions{
Board: image.BoardRandom,
Grid: image.GridRandom,
Piece: image.PieceRandom,
}
}
img, err := image.Generate(state, options)
if err != nil {
log.Errorf(ctx, "failed to generate: %s", err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
switch path.Ext(r.URL.Path) {
case ".jpg":
fallthrough
case ".jpeg":
w.Header().Set("Content-Type", "image/jpeg")
if err := jpeg.Encode(w, img, nil); err != nil {
log.Errorf(ctx, "failed to encode: %s", err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
case ".gif":
w.Header().Set("Content-Type", "image/gif")
if err := gif.Encode(w, img, nil); err != nil {
log.Errorf(ctx, "failed to encode: %s", err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
default:
w.Header().Set("Content-Type", "image/png")
if err := png.Encode(w, img); err != nil {
log.Errorf(ctx, "failed to encode: %s", err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}
}
runtime: go
api_version: go1
handlers:
- url: /.*
script: _go_app
automatic_scaling:
max_idle_instances: 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment