Last active
February 24, 2018 18:06
-
-
Save abackstrom/014d9e25d9147bbf56f5802a240cbfc8 to your computer and use it in GitHub Desktop.
This gist was created by the gisted code. Self-gisting! This is the first complete Go program I've ever written.
This file contains 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 ( | |
"bytes" | |
"encoding/json" | |
"flag" | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
"os" | |
"strings" | |
) | |
const ( | |
api_base = "https://api.github.com" | |
) | |
type GistFiles map[string]GistFile | |
type GistFile struct { | |
Content string `json:"content"` | |
} | |
type CreateGist struct { | |
Desc string `json:"description"` | |
Public bool `json:"public"` | |
Files GistFiles `json:"files"` | |
} | |
func jsonForFile(path string, contents string) []byte { | |
file := GistFile{ | |
Content: contents, | |
} | |
files := CreateGist{ | |
Desc: "", | |
Public: true, | |
Files: GistFiles{ | |
path: file, | |
}, | |
} | |
jsonVal, err := json.Marshal(files) | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
return jsonVal | |
} | |
func readGithubToken(path string) (string, error) { | |
if strings.HasPrefix(path, "~") { | |
home := os.Getenv("HOME") | |
path = home + path[1:] | |
} | |
contents, err := ioutil.ReadFile(path) | |
return strings.Split(string(contents), "\n")[0], err | |
} | |
func main() { | |
filename := flag.String("file", "", "target file") | |
flag.Parse() | |
if *filename == "" { | |
fmt.Println("-file must have a value") | |
os.Exit(1) | |
} | |
token, err := readGithubToken("~/.github_token") | |
contents, err := ioutil.ReadFile(*filename) | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
jsonVal := jsonForFile(*filename, string(contents)) | |
client := &http.Client{} | |
req, err := http.NewRequest("POST", api_base+"/gists", bytes.NewBuffer(jsonVal)) | |
req.Header.Add("Accept", "application/vnd.github.v3+json") | |
req.Header.Add("Authorization", "token "+token) | |
req.Header.Add("Content-Type", "application/json") | |
resp, err := client.Do(req) | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
if resp.StatusCode == 201 { | |
location, _ := resp.Location() | |
fmt.Println(location) | |
} else { | |
fmt.Println("Unexpected response code: " + resp.Status) | |
fmt.Println(resp) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment