Skip to content

Instantly share code, notes, and snippets.

@stephenmathieson
Created November 13, 2015 23:29
Show Gist options
  • Save stephenmathieson/148dc9f44bdf8d84a48d to your computer and use it in GitHub Desktop.
Save stephenmathieson/148dc9f44bdf8d84a48d to your computer and use it in GitHub Desktop.
go by example scaffold thing
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"regexp"
)
var fileTemplate = `
package main
import "fmt"
func main() {
}
`
var directoryFormat = "./examples/%02d-%s"
var fileFormat = "%s/main.go"
var expr = regexp.MustCompile(`<li><a href="([\w-]+)">`)
func main() {
html, err := request("https://gobyexample.com/")
check(err)
matches := expr.FindAllStringSubmatch(html, -1)
for i, name := range matches {
dirname := fmt.Sprintf(directoryFormat, i+1, name[1])
filename := fmt.Sprintf(fileFormat, dirname)
err := os.MkdirAll(dirname, 0777)
check(err)
fp, err := os.Create(filename)
check(err)
_, err = fp.WriteString(fileTemplate)
check(err)
defer fp.Close()
}
}
func check(e error) {
if e != nil {
panic(e)
}
}
func request(url string) (string, error) {
res, err := http.Get(url)
if err != nil {
return "", err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", err
}
html := string(body)
return html, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment