我是新手Golang
,请假设我有 2 种型号,如下所示
type Jobs struct {
JobID uint `json: "jobId" gorm:"primary_key;auto_increment"`
SourcePath string `json: "sourcePath"`
Priority int64 `json: "priority"`
InternalPriority string `json: "internalPriority"`
ExecutionEnvironmentID string `json: "executionEnvironmentID"`
}
type ExecutionEnvironment struct {
ExecutionEnvironmentId string `json: "executionEnvironmentID" gorm:"primary_key;auto_increment"`
CloudProviderType string `json: "cloudProviderType"`
InfrastructureType string `json: "infrastructureType"`
CloudRegion string `json: "cloudRegion"`
CreatedAt time.Time `json: "createdAt"`
}
这是我的Database connection
& get jobs
API 代码
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"time"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type Jobs struct {
JobID uint `json: "jobId" gorm:"primary_key;auto_increment"`
SourcePath string `json: "sourcePath"`
Priority int64 `json: "priority"`
InternalPriority string `json: "internalPriority"`
ExecutionEnvironmentID string `json: "executionEnvironmentID"`
}
type ExecutionEnvironment struct {
ExecutionEnvironmentId string `json: "executionEnvironmentID" gorm:"primary_key;auto_increment"`
CloudProviderType string `json: "cloudProviderType"`
InfrastructureType string `json: "infrastructureType"`
CloudRegion string `json: "cloudRegion"`
CreatedAt time.Time `json: "createdAt"`
}
var db *gorm.DB
func initDB() {
var err error
dataSourceName := "root:@tcp(localhost:3306)/?parseTime=True"
db, err = gorm.Open("mysql", dataSourceName)
if err != nil {
fmt.Println(err)
panic("failed to connect database")
}
//db.Exec("CREATE DATABASE test")
db.LogMode(true)
db.Exec("USE test")
db.AutoMigrate(&Jobs{}, &ExecutionEnvironment{})
}
func GetAllJobs(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Println("Executing Get All Jobs function")
// var jobs []Jobs
// db.Preload("jobs").Find(&jobs)
// json.NewEncoder(w).Encode(jobs)
var jobs []Jobs
if err := db.Table("jobs").Select("*").Joins("JOIN execution_environments on execution_environments.execution_environment_id = jobs.execution_environment_id").Find(&jobs).Error; err != nil {
fmt.Println(err)
}
json.NewEncoder(w).Encode(jobs)
}
func main() {
// router
router := mux.NewRouter()
// Access URL
router.HandleFunc("/GetAllJobs", GetAllJobs).Methods("GET")
// Initialize db connection
initDB()
// config port
fmt.Printf("Starting server at 8000 \n")
http.ListenAndServe(":8000", router)
}
在GetAllJobs
我尝试获取jobs
表数据和execution_environments
表数据。但我的代码不是fetch
execution_environments
表格数据。请检查以下示例json
:
[
{
"JobID": 4,
"SourcePath": "test1",
"Priority": 2,
"InternalPriority": "test",
"ExecutionEnvironmentID": "103"
}
]
请帮我获取我的execution_environments
表格数据json