Skip to content

Instantly share code, notes, and snippets.

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