Created
August 26, 2014 21:29
-
-
Save PirosB3/29849e1b972b1565633d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ReadClientID(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() { | |
filename := flag.String("name", "gist.txt", "file name and format") | |
public := flag.Bool("public", true, "gist should be public") | |
flag.Parse() | |
fileReader, errFileReader := ioutil.ReadFile("/Users/danielpiros/.gister") | |
if errFileReader != nil { | |
panic(errFileReader) | |
} | |
clientId, err := ReadClientID(fileReader) | |
file, err := ReadAndPackageFile(os.Stdin) | |
if err != nil { | |
panic("Error reading stdin contents.") | |
} | |
files := make(map[string]*GistFile) | |
files[*filename] = file | |
payload := &GistPayload{ | |
Public: *public, | |
Files: files, | |
} | |
jsonPayload, err := json.Marshal(payload) | |
if err != nil { | |
panic(err) | |
} | |
out := make(chan string) | |
go PostGist( | |
strings.NewReader(string(jsonPayload)), | |
clientId, | |
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