Advertisement
Guest User

migration

a guest
May 14th, 2019
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.69 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "database/sql"
  5.     "encoding/json"
  6.     "fmt"
  7.     "os"
  8.  
  9.     _ "github.com/go-sql-driver/mysql"
  10. )
  11.  
  12. //connect to database
  13. func dbConn() (db *sql.DB) {
  14.     dbDriver := "mysql"
  15.     dbUser := "root"
  16.     dbPass := "root"
  17.     dbName := "upwork"
  18.     db, err := sql.Open(dbDriver, dbUser+":"+dbPass+"@/"+dbName)
  19.     if err != nil {
  20.         panic(err.Error())
  21.     }
  22.     return db
  23. }
  24.  
  25. type topicItem struct {
  26.     Id        int    `json:"id"`
  27.     FileExist bool   `json:"file_exist`
  28.     ItemPiLoc string `json:"item_pi_loc"`
  29. }
  30.  
  31. type Result struct {
  32.     Status   bool        `json:"status"`
  33.     Response interface{} `json:"response"`
  34.     Error    string      `json:"error"`
  35. }
  36.  
  37. func getVideoDetail(data []int) (Result, error) {
  38.     var id int
  39.     var itemPiLoc string
  40.     db := dbConn()
  41.     // we need define field list when run select query as will need for scan method
  42.     sqlStatement := `SELECT id,item_pi_loc FROM TopicItems WHERE item_id =? and item_type_id= 1 order by item_order;`
  43.     row := db.QueryRow(sqlStatement, data[1])
  44.  
  45.     result := Result{}
  46.  
  47.     switch err := row.Scan(&id, &itemPiLoc); err {
  48.     case nil:
  49.         fileName := "..%sCourseResource%s%d%svideos%s%d%s%s"
  50.         dirPath := string(os.PathSeparator)
  51.         fileName = fmt.Sprintf(fileName, dirPath, dirPath, data[0], dirPath, dirPath, data[1], dirPath, itemPiLoc)
  52.         topic := topicItem{Id: id, ItemPiLoc: itemPiLoc}
  53.         if _, err := os.Stat(fileName); err == nil {
  54.             topic.FileExist = true
  55.         }
  56.         result.Status = true
  57.         result.Response = topic
  58.     default:
  59.         result.Response = nil
  60.         result.Error = err.Error()
  61.     }
  62.     return result, nil
  63. }
  64.  
  65. func main() {
  66.     data := []int{2, 1}
  67.     result, _ := getVideoDetail(data)
  68.  
  69.     response, _ := json.Marshal(result)
  70.  
  71.     fmt.Println(string(response))
  72.  
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement