Last active
February 27, 2018 18:48
-
-
Save montanaflynn/bb002f8212e9cc7f75af5cc03e7a5fd8 to your computer and use it in GitHub Desktop.
Write the current time to an image from a google cloud function in Go
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 ( | |
"flag" | |
"net/http" | |
"time" | |
"github.com/fogleman/gg" | |
"github.com/golang/freetype/truetype" | |
"golang.org/x/image/font/gofont/goregular" | |
"./nodego" | |
) | |
func init() { | |
nodego.OverrideLogger() | |
} | |
func handler(w http.ResponseWriter, r *http.Request) { | |
// create a blank white canvas | |
height := 200 | |
width := 600 | |
canvas := gg.NewContext(width, height) | |
canvas.SetRGB(1, 1, 1) | |
// clear the white canvas and set the foreground to black | |
canvas.Clear() | |
canvas.SetRGB(0, 0, 0) | |
// parse the go font from standard library | |
font, err := truetype.Parse(goregular.TTF) | |
if err != nil { | |
// nodego.ErrorLogger.Println(err) | |
return | |
} | |
// create a new font and set it's size | |
fontFace := truetype.NewFace(font, &truetype.Options{ | |
Size: 36, | |
}) | |
canvas.SetFontFace(fontFace) | |
// get current time and format it in UTC timezone | |
now := time.Now() | |
timeString := now.UTC().Format("2006-01-02 15:04:05 MST") | |
// write the current time to the canvas | |
canvas.DrawStringAnchored(timeString, float64(width/2), float64(height/2), 0.5, 0.5) | |
// encode the image as a png and write to response | |
w.WriteHeader(200) | |
err = canvas.EncodePNG(w) | |
if err != nil { | |
// nodego.ErrorLogger.Println(err) | |
return | |
} | |
} | |
func main() { | |
flag.Parse() | |
http.HandleFunc(nodego.HTTPTrigger, nodego.WithLoggerFunc(handler)) | |
nodego.TakeOver() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment