Skip to content

Break long code sample into smaller pieces #1

@xrd

Description

@xrd

Section: https://github.com/xrd/advanced-github-oreilly/blob/jpoz/chapter-10-go.asciidoc#setting-up-our-webhooks-endpoint

I don't know how the long code snippet will read in a book format, as it might stretch into multiple pages. I had a lengthy code section in the android chapter (https://github.com/xrd/advanced-github-oreilly/blob/master/chapter-07-android.asciidoc#code-to-talk-to-github). I ended up breaking the large main function into a bunch of small subroutines, discussing the high level main function, and then having a different smaller section for each of the necessary subroutines. Something like this abbreviated main routine with the functions like main, webhookHandler and the others functions tubbed out. Then you could discuss the strategy after displaying this code snippet and afterwards have a level 3 header which discusses the implementation (and show the code sample) for each function. If you want me to take a stab at refactoring this, I'd be happy to.

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"
    "os/exec"

    "code.google.com/p/goauth2/oauth"
    "github.com/google/go-github/github"
)

var (
    accessToken = os.Getenv("GITHUB_ACCESS_TOKEN")
    transport   = &oauth.Transport{Token: &oauth.Token{AccessToken: accessToken}}
    client      = github.NewClient(transport.Client())
)

func main() {
    http.HandleFunc("/webhook", webhookHandler)

    fmt.Println("Listening on 4567")
    err := http.ListenAndServe(":4567", nil)
    fmt.Println(err)
}

func webhookHandler(w http.ResponseWriter, r *http.Request) {
    eventType := r.Header.Get("X-GitHub-Event")
    log.Printf("Received: %s event", eventType)

    if eventType != "push" {
        return
    }

    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        fmt.Println(err)
        return
    }

    payload := github.WebHookPayload{}
    json.Unmarshal(body, &payload)

  go run(payload)

    fmt.Fprintln(w, "OK")
    log.Printf("Responded: OK")
}

func run(payload github.WebHookPayload) {
  buffer, err := runMakeTest(payload)
  if err != nil {
    log.Printf("runMakeTest: %s", err)
  }

  log.Printf("%s", buffer)

  resp, err := commentOutput(payload, buffer)
  if err != nil {
    log.Printf("commentOutput: %s\n%s", err, resp.Body)
    return
  }
  log.Printf("Commented on: %s", *payload.HeadCommit.ID)
}

func runMakeTest(payload github.WebHookPayload) (*bytes.Buffer, error) {

}

func commentOutput(payload github.WebHookPayload, output *bytes.Buffer) (*github.Response, error) {

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions