Skip to content

Instantly share code, notes, and snippets.

@CaptainBern
Last active May 18, 2016 16:24
Show Gist options
  • Save CaptainBern/78c52a0f50427ce851fc to your computer and use it in GitHub Desktop.
Save CaptainBern/78c52a0f50427ce851fc to your computer and use it in GitHub Desktop.
Little program written in Go to upload stuff to hastebin.com
package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
)
const VERSION string = "0.0.1"
const HASTEBIN_URL string = "http://hastebin.com/"
type Response struct {
Key string `json:"key"`
}
var useRaw = flag.Bool("raw", false, "Return an url which points to the raw-text of the upload.")
func init() {
flag.Usage = func() {
fmt.Println("=============[Haze]=============")
fmt.Println("Usage:")
fmt.Println(" haze [-r]")
fmt.Println(" -r: Returns an url which points to the raw-text of the upload.")
fmt.Println("Example: ")
fmt.Println(" ./haze <file>")
fmt.Println(" (Keep in mind that the file-param should *always* be first)")
fmt.Println("You can also use pipes, eg:")
fmt.Println(" echo 'test' | ./haze -r")
fmt.Println("--------------------------------")
os.Exit(-1)
}
flag.BoolVar(useRaw, "r", false, "Returns an url which points to the raw-text of the upload.")
flag.Parse()
}
func main() {
var data []byte
var err error
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
data, err = ioutil.ReadAll(os.Stdin)
} else {
fileName := os.Args[1]
data, err = ioutil.ReadFile(fileName)
}
if err != nil {
panic(err)
}
response, err := uploadRaw(string(data))
if err != nil {
panic(err)
}
printResult(response)
os.Exit(0)
}
func uploadRaw(data string) (response Response, err error) {
response = Response{}
buffer := bytes.NewBuffer([]byte(data))
req, err := http.NewRequest("POST", HASTEBIN_URL+"documents", buffer)
req.Header.Set("User-Agent", "Mozilla/5.0")
req.Header.Set("Content-Type", "text")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode == 200 {
bytes, ioerr := ioutil.ReadAll(resp.Body)
if ioerr != nil {
err = ioerr
return
}
err = json.Unmarshal(bytes, &response)
return
} else {
err = errors.New("Response-code was not 200!")
return
}
}
func printResult(response Response) {
var result string
if *useRaw {
result = fmt.Sprintf("%s%s%s", HASTEBIN_URL, "raw/", response.Key)
} else {
result = fmt.Sprintf("%s%s", HASTEBIN_URL, response.Key)
}
fmt.Println("result: ", result)
}
@flyinggoatman
Copy link

How do you run it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment