Skip to content

Instantly share code, notes, and snippets.

@PirosB3
Created August 26, 2014 22:45
Show Gist options
  • Save PirosB3/ebdd92d0cc18074dc05c to your computer and use it in GitHub Desktop.
Save PirosB3/ebdd92d0cc18074dc05c to your computer and use it in GitHub Desktop.
package main
import (
"errors"
"fmt"
"encoding/json"
"os"
"io"
"io/ioutil"
"flag"
"net/http"
"strings"
)
const (
TOKEN_KEY = "token"
GITHUB_GIST_URL = "https://api.github.com/gists"
)
type GistFile struct {
Content string `json:"content"`
}
type GistPayload struct {
Public bool `json:"public"`
Files map[string]*GistFile `json:"files"`
}
func ReadToken(bytes []byte) (string, error) {
var data map[string]interface{}
err := json.Unmarshal(bytes, &data)
if err != nil {
return "", err
}
if data[TOKEN_KEY] == nil {
return "", errors.New(fmt.Sprintf("JSON does not contain %s", TOKEN_KEY))
}
return data[TOKEN_KEY].(string), nil
}
func main() {
out := make(chan string)
files := make(map[string]*GistFile)
filename := flag.String("name", "gist.txt", "file name and format")
public := flag.Bool("public", true, "gist should be public")
flag.Parse()
// Read Token
fileReader, errFileReader := ioutil.ReadFile("/Users/danielpiros/.gister")
if errFileReader != nil {
panic(errFileReader)
}
token, err := ReadToken(fileReader)
// Read file from stdin
file, err := ReadAndPackageFile(os.Stdin)
if err != nil {
panic("Error reading stdin contents.")
}
// Package file in a GistPayload
files[*filename] = file
payload := &GistPayload{
Public: *public,
Files: files,
}
jsonPayload, _ := json.Marshal(payload)
go PostGist(strings.NewReader(string(jsonPayload)), token, out)
gistUrl := <- out
fmt.Println(gistUrl)
}
func PostGist(payload io.Reader, token string, out chan(string)) {
url := GITHUB_GIST_URL
url += fmt.Sprintf("?access_token=%s", token)
request, _ := http.NewRequest("POST", url, payload)
client := &http.Client{}
response, _ := client.Do(request)
var jsonResponse map[string]interface{}
jsonResponseString, _ := ioutil.ReadAll(response.Body)
json.Unmarshal(jsonResponseString, &jsonResponse)
out <- jsonResponse["html_url"].(string)
}
func ReadAndPackageFile(in io.Reader) (*GistFile, error) {
bytes, err := ioutil.ReadAll(in)
if err != nil{
return nil, err
}
res := &GistFile{
Content: string(bytes),
}
return res, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment