a simple url shortener in Go (check it out at qurl.org)
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.

86 lines
1.5 KiB

6 years ago
4 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "git.binarythought.com/cdramey/qurl/obj"
  6. "git.binarythought.com/cdramey/qurl/storage"
  7. "net"
  8. "os"
  9. "time"
  10. )
  11. type qurljson struct {
  12. ID uint64 `json:"id"`
  13. IP string `json:"ip"`
  14. Browser string `json:"browser"`
  15. URL string `json:"url"`
  16. Date struct {
  17. Date int64 `json:"$date"`
  18. } `json:"date"`
  19. }
  20. func loadjson(stor storage.Storage, filename string) error {
  21. file, err := os.Open(filename)
  22. if err != nil {
  23. return fmt.Errorf("Error opening %s: %s", filename, err.Error())
  24. }
  25. defer file.Close()
  26. var qj []qurljson
  27. decoder := json.NewDecoder(file)
  28. err = decoder.Decode(&qj)
  29. if err != nil {
  30. return fmt.Errorf("Error parsing %s: %s", filename, err.Error())
  31. }
  32. fmt.Printf("Parsing %d qurls.. \n", len(qj))
  33. var max uint64 = 0
  34. var count uint64 = 0
  35. for _, e := range qj {
  36. if e.ID > max {
  37. max = e.ID
  38. }
  39. q := &obj.QURL{
  40. ID: e.ID,
  41. URL: e.URL,
  42. }
  43. if e.Date.Date > 0 {
  44. q.Created = time.Unix((e.Date.Date / 1000), 0)
  45. }
  46. if e.IP != "" {
  47. q.IP = net.ParseIP(e.IP)
  48. }
  49. if e.Browser != "" {
  50. q.Browser = e.Browser
  51. }
  52. err := q.CheckValid()
  53. if err != nil {
  54. fmt.Printf("\n%s\nValidation failure: %s\n", q.URL, err.Error())
  55. continue
  56. }
  57. err = stor.AddQURL(q)
  58. if err != nil {
  59. return fmt.Errorf("AddQURL() Database error: %s", err.Error())
  60. }
  61. count++
  62. if (count % 100) == 0 {
  63. fmt.Printf("*")
  64. }
  65. }
  66. err = stor.SetQURLSequence(max)
  67. if err != nil {
  68. return fmt.Errorf("Error setting sequence: %s", err.Error())
  69. }
  70. fmt.Printf("\nDone!\n")
  71. return nil
  72. }