Guest User

Untitled

a guest
May 30th, 2018
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. ```golang
  2. package main
  3.  
  4. import (
  5. "fmt"
  6. "log"
  7. "os"
  8. "strconv"
  9. "time"
  10. "io/ioutil"
  11.  
  12. _ "github.com/go-sql-driver/mysql"
  13. "github.com/jmoiron/sqlx"
  14. )
  15.  
  16. var (
  17. db *sqlx.DB
  18. )
  19.  
  20. type Post struct {
  21. ID int `db:"id"`
  22. UserID int `db:"user_id"`
  23. Imgdata []byte `db:"imgdata"`
  24. Body string `db:"body"`
  25. Mime string `db:"mime"`
  26. CreatedAt time.Time `db:"created_at"`
  27. CommentCount int
  28. CSRFToken string
  29. }
  30.  
  31. func main() {
  32. host := os.Getenv("ISUCONP_DB_HOST")
  33. if host == "" {
  34. host = "localhost"
  35. }
  36. port := os.Getenv("ISUCONP_DB_PORT")
  37. if port == "" {
  38. port = "3306"
  39. }
  40. _, err := strconv.Atoi(port)
  41. if err != nil {
  42. log.Fatalf("Failed to read DB port number from an environment variable ISUCONP_DB_PORT.\nError: %s", err.Error())
  43. }
  44. user := os.Getenv("ISUCONP_DB_USER")
  45. if user == "" {
  46. user = "root"
  47. }
  48. password := os.Getenv("ISUCONP_DB_PASSWORD")
  49. dbname := os.Getenv("ISUCONP_DB_NAME")
  50. if dbname == "" {
  51. dbname = "isuconp"
  52. }
  53.  
  54. dsn := fmt.Sprintf(
  55. "%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true&loc=Local",
  56. user,
  57. password,
  58. host,
  59. port,
  60. dbname,
  61. )
  62.  
  63. db, err = sqlx.Open("mysql", dsn)
  64. if err != nil {
  65. log.Fatalf("Failed to connect to DB: %s.", err.Error())
  66. }
  67. defer db.Close()
  68.  
  69. post := Post{}
  70. sum := 10036
  71. var filename = ""
  72. for i := 0; i < sum; i++ {
  73. fmt.Println("%d:", i)
  74. derr := db.Get(&post, "SELECT `id`, `user_id`, `mime`, `imgdata`, `body`, `created_at` FROM `posts` WHERE `id` = ?", i)
  75. if derr != nil {
  76. fmt.Println(derr.Error())
  77. continue
  78. }
  79. if post.Mime == "image/jpeg" {
  80. filename = fmt.Sprintf("%d.jpg", i)
  81. } else if post.Mime == "image/png" {
  82. filename = fmt.Sprintf("%d.png", i)
  83. } else if post.Mime == "image/gif" {
  84. filename = fmt.Sprintf("%d.gif", i)
  85. } else {
  86. continue;
  87. }
  88. fmt.Println("%s", filename)
  89. //fmt.Println("%s", post.Body)
  90. ioutil.WriteFile(filename, post.Imgdata, 0644)
  91. // w.Header().Set("Content-Type", post.Mime)
  92. //fmt.Println(filename)
  93. // _, err := w.filename);
  94. // if err != nil {
  95. // fmt.Println(err.Error())
  96. // }
  97. }
  98.  
  99. }
  100.  
  101.  
  102. ```
Add Comment
Please, Sign In to add comment