Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ```golang
- package main
- import (
- "fmt"
- "log"
- "os"
- "strconv"
- "time"
- "io/ioutil"
- _ "github.com/go-sql-driver/mysql"
- "github.com/jmoiron/sqlx"
- )
- var (
- db *sqlx.DB
- )
- type Post struct {
- ID int `db:"id"`
- UserID int `db:"user_id"`
- Imgdata []byte `db:"imgdata"`
- Body string `db:"body"`
- Mime string `db:"mime"`
- CreatedAt time.Time `db:"created_at"`
- CommentCount int
- CSRFToken string
- }
- func main() {
- host := os.Getenv("ISUCONP_DB_HOST")
- if host == "" {
- host = "localhost"
- }
- port := os.Getenv("ISUCONP_DB_PORT")
- if port == "" {
- port = "3306"
- }
- _, err := strconv.Atoi(port)
- if err != nil {
- log.Fatalf("Failed to read DB port number from an environment variable ISUCONP_DB_PORT.\nError: %s", err.Error())
- }
- user := os.Getenv("ISUCONP_DB_USER")
- if user == "" {
- user = "root"
- }
- password := os.Getenv("ISUCONP_DB_PASSWORD")
- dbname := os.Getenv("ISUCONP_DB_NAME")
- if dbname == "" {
- dbname = "isuconp"
- }
- dsn := fmt.Sprintf(
- "%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true&loc=Local",
- user,
- password,
- host,
- port,
- dbname,
- )
- db, err = sqlx.Open("mysql", dsn)
- if err != nil {
- log.Fatalf("Failed to connect to DB: %s.", err.Error())
- }
- defer db.Close()
- post := Post{}
- sum := 10036
- var filename = ""
- for i := 0; i < sum; i++ {
- fmt.Println("%d:", i)
- derr := db.Get(&post, "SELECT `id`, `user_id`, `mime`, `imgdata`, `body`, `created_at` FROM `posts` WHERE `id` = ?", i)
- if derr != nil {
- fmt.Println(derr.Error())
- continue
- }
- if post.Mime == "image/jpeg" {
- filename = fmt.Sprintf("%d.jpg", i)
- } else if post.Mime == "image/png" {
- filename = fmt.Sprintf("%d.png", i)
- } else if post.Mime == "image/gif" {
- filename = fmt.Sprintf("%d.gif", i)
- } else {
- continue;
- }
- fmt.Println("%s", filename)
- //fmt.Println("%s", post.Body)
- ioutil.WriteFile(filename, post.Imgdata, 0644)
- // w.Header().Set("Content-Type", post.Mime)
- //fmt.Println(filename)
- // _, err := w.filename);
- // if err != nil {
- // fmt.Println(err.Error())
- // }
- }
- }
- ```
Add Comment
Please, Sign In to add comment