Created
September 9, 2019 23:13
-
-
Save gopher1980/a5fc78dcb6aba6147f93b23a79f5f749 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"flag" | |
"fmt" | |
"log" | |
"net/http" | |
"time" | |
"github.com/gorilla/mux" | |
"github.com/jinzhu/gorm" | |
_ "github.com/jinzhu/gorm/dialects/mysql" | |
_ "github.com/jinzhu/gorm/dialects/postgres" | |
_ "github.com/jinzhu/gorm/dialects/sqlite" | |
) | |
var suffix string | |
type Record struct { | |
ID uint `gorm:"primarykey" ` | |
CreatedAt time.Time | |
UpdatedAt time.Time | |
DeletedAt *time.Time | |
Name string `json:"name" ` | |
} | |
func (e Record) TableName() string { | |
name := "record" + suffix | |
fmt.Println(name) | |
return name | |
} | |
func main() { | |
var uridb string | |
var drivedb string | |
var addr string | |
var debug bool | |
flag.StringVar(&drivedb, "drive", "sqlite3", "[sqlite3, mysql, postgres ]") | |
flag.StringVar(&uridb, "db", "test.db", "Uri of db") | |
flag.StringVar(&addr, "addr", ":9090", "this is addr of this ListenAndServe") | |
flag.BoolVar(&debug, "debug", false, "sql debug") | |
flag.Parse() | |
var err error | |
db, err := gorm.Open(drivedb, uridb) | |
if err != nil { | |
panic("failed to connect database") | |
} | |
defer db.Close() | |
suffix = "1" | |
db.AutoMigrate(&Record{}) | |
suffix = "2" | |
db.AutoMigrate(&Record{}) | |
db.Table("record1").Save(&Record{Name: "data 1"}) | |
db.Table("record2").Save(&Record{Name: "data 2"}) | |
if drivedb == "sqlite3" { | |
db.Exec("PRAGMA foreign_keys = ON;") | |
} | |
r := mux.NewRouter() | |
r.HandleFunc("/api/v1/record/1", func(writer http.ResponseWriter, request *http.Request) { | |
r := []Record{} | |
db.Table("record1").Find(&r) | |
json.NewEncoder(writer).Encode(r) | |
return | |
}).Methods(http.MethodGet) | |
r.HandleFunc("/api/v1/record/2", func(writer http.ResponseWriter, request *http.Request) { | |
r := []Record{} | |
db.Table("record2").Find(&r) | |
json.NewEncoder(writer).Encode(r) | |
return | |
}).Methods(http.MethodGet) | |
http.Handle("/", r) | |
log.Fatal(http.ListenAndServe(addr, nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment