Skip to content

Instantly share code, notes, and snippets.

@funglaub
Created April 20, 2012 22:47
Show Gist options
  • Save funglaub/2432437 to your computer and use it in GitHub Desktop.
Save funglaub/2432437 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
)
// type Request struct {
// LongUrl string "longUrl" // Annoying, only capital letter fields are exported by json.Marshal
// }
type Response struct {
Kind string
Id string
LongUrl string
}
func main() {
flag.Parse()
if flag.NArg() < 1 {
fmt.Fprintln(os.Stderr, "No URL given! Bye!")
os.Exit(-1)
}
url, error := googl(flag.Arg(0))
if error != nil {
fmt.Fprintln(os.Stderr, error)
os.Exit(-1)
}
fmt.Printf("%s -> %s\n", flag.Arg(0), url)
}
func googl(long_url string) (url string, err error) {
remote_url := "https://www.googleapis.com/urlshortener/v1/url"
// request := Request{long_url}
// b, err := json.Marshal(request)
// if err != nil {
// return
// }
// buf := bytes.NewBuffer(b)
buf := bytes.NewBufferString("{\"longUrl\": \"" + long_url + "\"}")
resp, err := http.Post(remote_url, "application/json", buf)
if err != nil {
return
}
b, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != 200 {
return "", errors.New("bad response status code")
}
var response Response
err = json.Unmarshal(b, &response)
if err != nil {
return
}
url = response.Id
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment