|
| 1 | +// Copyright 2020 The golang.design Initiative authors. |
| 2 | +// All rights reserved. Use of this source code is governed |
| 3 | +// by a GNU GPL-3.0 license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package main |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "fmt" |
| 10 | + "io/ioutil" |
| 11 | + "math" |
| 12 | + "net/http" |
| 13 | + "net/url" |
| 14 | + "os" |
| 15 | + "os/signal" |
| 16 | + "syscall" |
| 17 | + "time" |
| 18 | + |
| 19 | + "github.com/chromedp/cdproto/cdp" |
| 20 | + "github.com/chromedp/cdproto/dom" |
| 21 | + "github.com/chromedp/cdproto/emulation" |
| 22 | + "github.com/chromedp/cdproto/page" |
| 23 | + "github.com/chromedp/chromedp" |
| 24 | + "github.com/gin-gonic/gin" |
| 25 | + "github.com/google/uuid" |
| 26 | + "github.com/sirupsen/logrus" |
| 27 | +) |
| 28 | + |
| 29 | +func main() { |
| 30 | + router := gin.Default() |
| 31 | + router.Static("/api/v1/code2img/data/images", "./data/images") |
| 32 | + router.POST("/api/v1/code2img", code2img) |
| 33 | + s := &http.Server{Addr: ":8080", Handler: router} |
| 34 | + |
| 35 | + go func() { |
| 36 | + if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed { |
| 37 | + logrus.Fatalf("listen: %s\n", err) |
| 38 | + } |
| 39 | + }() |
| 40 | + |
| 41 | + quit := make(chan os.Signal) |
| 42 | + signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) |
| 43 | + <-quit |
| 44 | + logrus.Println("shutting down...") |
| 45 | + |
| 46 | + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 47 | + defer cancel() |
| 48 | + if err := s.Shutdown(ctx); err != nil { |
| 49 | + logrus.Fatal("forced to shutdown: ", err) |
| 50 | + } |
| 51 | + logrus.Println("server exiting, good bye!") |
| 52 | +} |
| 53 | + |
| 54 | +type form struct { |
| 55 | + Code string `json:"code"` |
| 56 | +} |
| 57 | + |
| 58 | +func code2img(c *gin.Context) { |
| 59 | + b := form{} |
| 60 | + if err := c.ShouldBindJSON(&b); err != nil { |
| 61 | + c.String(http.StatusBadRequest, fmt.Sprintf("Error: %s", err)) |
| 62 | + return |
| 63 | + } |
| 64 | + id := uuid.New().String() |
| 65 | + gofile := "./data/code/" + id + ".go" |
| 66 | + |
| 67 | + err := ioutil.WriteFile(gofile, []byte(b.Code), os.ModePerm) |
| 68 | + if err != nil { |
| 69 | + logrus.Errorf("[%s]: write file error %v", gofile, err) |
| 70 | + c.String(http.StatusBadRequest, fmt.Sprintf("Error: %s", err)) |
| 71 | + return |
| 72 | + } |
| 73 | + |
| 74 | + err = render("./data/images/"+id+".png", b.Code) |
| 75 | + if err != nil { |
| 76 | + c.String(http.StatusBadRequest, fmt.Sprintf("Error: %s", err)) |
| 77 | + return |
| 78 | + } |
| 79 | + |
| 80 | + c.String(http.StatusOK, "https://golang.design/api/v1/code2img/data/images/"+id+".png") |
| 81 | +} |
| 82 | + |
| 83 | +func render(imgfile, code string) error { |
| 84 | + // https://carbon.now.sh/? |
| 85 | + // bg=rgba(74%2C144%2C226%2C1)& |
| 86 | + // t=material& |
| 87 | + // wt=none& |
| 88 | + // l=auto& |
| 89 | + // ds=true& |
| 90 | + // dsyoff=0px& |
| 91 | + // dsblur=29px& |
| 92 | + // wc=true& |
| 93 | + // wa=true& |
| 94 | + // pv=28px& |
| 95 | + // ph=100px& |
| 96 | + // ln=true& |
| 97 | + // fl=1& |
| 98 | + // fm=Source%20Code%20Pro& |
| 99 | + // fs=13.5px& |
| 100 | + // lh=152%25& |
| 101 | + // si=false& |
| 102 | + // es=2x& |
| 103 | + // wm=false& |
| 104 | + // code=func%2520main() |
| 105 | + var carbonOptions = map[string]string{ |
| 106 | + "bg": "rgba(74,144,226,1)", // backgroundColor |
| 107 | + "t": "material", // theme |
| 108 | + "wt": "none", // windowTheme |
| 109 | + "l": "auto", // language |
| 110 | + "ds": "true", // dropShadow |
| 111 | + "dsyoff": "0px", // dropShadowOffsetY |
| 112 | + "dsblur": "29px", // dropShadowBlurRadius |
| 113 | + "wc": "true", // windowControls |
| 114 | + "wa": "true", // widthAdjustment |
| 115 | + "pv": "28px", // paddingVertical |
| 116 | + "ph": "100px", // paddingHorizontal |
| 117 | + "ln": "true", // lineNumbers |
| 118 | + "fl": "1", // firstLineNumber |
| 119 | + "fm": "Source Code Pro", // fontFamily |
| 120 | + "fs": "13.5px", // fontSize |
| 121 | + "lh": "152%", // lineHeight |
| 122 | + "si": "false", //squaredImage |
| 123 | + "es": "2x", // exportSize |
| 124 | + "wm": "false", // watermark |
| 125 | + } |
| 126 | + |
| 127 | + values := url.Values{} |
| 128 | + for k, v := range carbonOptions { |
| 129 | + values.Set(k, v) |
| 130 | + } |
| 131 | + codeparam := url.Values{} |
| 132 | + codeparam.Set("code", code) |
| 133 | + |
| 134 | + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) |
| 135 | + defer cancel() |
| 136 | + ctx, cancel = chromedp.NewContext(ctx) |
| 137 | + defer cancel() |
| 138 | + |
| 139 | + url := "https://carbon.now.sh/?" + values.Encode() + "&" + codeparam.Encode() |
| 140 | + |
| 141 | + var picbuf []byte |
| 142 | + sel := "#export-container .container-bg" |
| 143 | + err := chromedp.Run(ctx, chromedp.Tasks{ |
| 144 | + chromedp.Navigate(url), |
| 145 | + screenshot(sel, &picbuf, chromedp.NodeReady, chromedp.ByID), |
| 146 | + }) |
| 147 | + if err != nil { |
| 148 | + return fmt.Errorf("render task error: %w", err) |
| 149 | + } |
| 150 | + |
| 151 | + err = ioutil.WriteFile(imgfile, picbuf, os.ModePerm) |
| 152 | + if err != nil { |
| 153 | + logrus.Errorf("[%s]: write screenshot error %v", imgfile, err) |
| 154 | + return err |
| 155 | + } |
| 156 | + return nil |
| 157 | +} |
| 158 | + |
| 159 | +func screenshot(sel interface{}, picbuf *[]byte, opts ...chromedp.QueryOption) chromedp.QueryAction { |
| 160 | + if picbuf == nil { |
| 161 | + panic("picbuf cannot be nil") |
| 162 | + } |
| 163 | + |
| 164 | + return chromedp.QueryAfter(sel, func(ctx context.Context, nodes ...*cdp.Node) error { |
| 165 | + if len(nodes) < 1 { |
| 166 | + return fmt.Errorf("selector %q did not return any nodes", sel) |
| 167 | + } |
| 168 | + |
| 169 | + // get layout metrics |
| 170 | + _, _, contentSize, err := page.GetLayoutMetrics().Do(ctx) |
| 171 | + if err != nil { |
| 172 | + return err |
| 173 | + } |
| 174 | + |
| 175 | + width, height := int64(math.Ceil(contentSize.Width)), int64(math.Ceil(contentSize.Height)) |
| 176 | + |
| 177 | + // force viewport emulation |
| 178 | + err = emulation.SetDeviceMetricsOverride(width, height, 1, false). |
| 179 | + WithScreenOrientation(&emulation.ScreenOrientation{ |
| 180 | + Type: emulation.OrientationTypePortraitPrimary, |
| 181 | + Angle: 0, |
| 182 | + }). |
| 183 | + Do(ctx) |
| 184 | + if err != nil { |
| 185 | + return err |
| 186 | + } |
| 187 | + |
| 188 | + // get box model |
| 189 | + box, err := dom.GetBoxModel().WithNodeID(nodes[0].NodeID).Do(ctx) |
| 190 | + if err != nil { |
| 191 | + return err |
| 192 | + } |
| 193 | + if len(box.Margin) != 8 { |
| 194 | + return chromedp.ErrInvalidBoxModel |
| 195 | + } |
| 196 | + |
| 197 | + // take screenshot of the box |
| 198 | + buf, err := page.CaptureScreenshot(). |
| 199 | + WithFormat(page.CaptureScreenshotFormatPng). |
| 200 | + WithClip(&page.Viewport{ |
| 201 | + X: math.Round(box.Margin[0]), |
| 202 | + Y: math.Round(box.Margin[1]), |
| 203 | + Width: math.Round(box.Margin[4] - box.Margin[0]), |
| 204 | + Height: math.Round(box.Margin[5] - box.Margin[1]), |
| 205 | + Scale: 1.0, |
| 206 | + }).Do(ctx) |
| 207 | + if err != nil { |
| 208 | + return err |
| 209 | + } |
| 210 | + |
| 211 | + *picbuf = buf |
| 212 | + return nil |
| 213 | + }, append(opts, chromedp.NodeVisible)...) |
| 214 | +} |
0 commit comments