Contains the Concourse pipeline definition for building a line-server container
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
1.8 KiB

  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "net/http"
  7. "github.com/zenazn/goji/web"
  8. )
  9. type shortenerRequest struct {
  10. LongURL string `json:"longUrl"`
  11. }
  12. type shortenerResponse struct {
  13. Kind string `json:"kind"`
  14. ID string `json:"id"`
  15. LongURL string `json:"longUrl"`
  16. Error struct {
  17. Code int `json:"code"`
  18. Message string `json:"message"`
  19. } `json:"error"`
  20. }
  21. func shortURLHandler(c web.C, w http.ResponseWriter, r *http.Request) {
  22. fileName := c.URLParams["name"]
  23. err := checkFile(fileName)
  24. if err == NotFoundErr {
  25. notFoundHandler(c, w, r)
  26. return
  27. }
  28. metadata, err := metadataRead(fileName)
  29. if err != nil {
  30. oopsHandler(c, w, r, RespJSON, "Corrupt metadata.")
  31. return
  32. }
  33. if metadata.ShortURL == "" {
  34. url, err := shortenURL(getSiteURL(r) + fileName)
  35. if err != nil {
  36. oopsHandler(c, w, r, RespJSON, err.Error())
  37. return
  38. }
  39. metadata.ShortURL = url
  40. err = metadataWrite(fileName, &metadata)
  41. if err != nil {
  42. oopsHandler(c, w, r, RespJSON, "Corrupt metadata.")
  43. return
  44. }
  45. }
  46. js, _ := json.Marshal(map[string]string{
  47. "shortUrl": metadata.ShortURL,
  48. })
  49. w.Write(js)
  50. return
  51. }
  52. func shortenURL(url string) (string, error) {
  53. apiURL := "https://www.googleapis.com/urlshortener/v1/url?key=" + Config.googleShorterAPIKey
  54. jsonStr, _ := json.Marshal(shortenerRequest{LongURL: url})
  55. req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(jsonStr))
  56. req.Header.Set("Content-Type", "application/json")
  57. client := &http.Client{}
  58. resp, err := client.Do(req)
  59. if err != nil {
  60. return "", err
  61. }
  62. defer resp.Body.Close()
  63. shortenerResponse := new(shortenerResponse)
  64. err = json.NewDecoder(resp.Body).Decode(shortenerResponse)
  65. if err != nil {
  66. return "", err
  67. }
  68. if shortenerResponse.Error.Message != "" {
  69. return "", errors.New(shortenerResponse.Error.Message)
  70. }
  71. return shortenerResponse.ID, nil
  72. }