Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package controllers
- import (
- "database/sql"
- "encoding/json"
- "errors"
- "fmt"
- "log"
- "net/http"
- "os"
- "strconv"
- "time"
- "github.com/gorilla/mux"
- "github.com/jinzhu/gorm"
- _ "github.com/jinzhu/gorm/dialects/postgres"
- _ "github.com/lib/pq"
- _ "gitlab.torq.trans.apps.ge.com/503081542/k-auth-api/models"
- "gitlab.torq.trans.apps.ge.com/torq/torq-auth-api/models"
- )
- var err error
- type API struct {
- Database *gorm.DB
- Router *mux.Router
- }
- func (api *API) Initialize(opts string) {
- // Initialize DB
- var driver = "postgres"
- var host = os.Getenv("DB_HOST")
- var dbname = os.Getenv("DB_NAME")
- var user = os.Getenv("DB_USER")
- var password = os.Getenv("DB_PASSWORD")
- var port = os.Getenv("DB_PORT")
- var conn = fmt.Sprintf("host=%v dbname=%v user=%v password=%v port=%v sslmode=disable", host, dbname, user, password, port)
- api.Database, err = gorm.Open(driver, conn)
- if err != nil {
- log.Print("failed to connect to the database")
- log.Fatal(err)
- }
- fmt.Println("Connection established")
- log.Printf("Postgres started at %s PORT", port)
- // MODELS
- type Application struct {
- ID string `json:"id" gorm:"primary_key"`
- AccessId int64
- CreatedAt time.Time `json:"-"`
- UpdatedAt time.Time `json:"-"`
- Name string `json:"name"`
- Ci string `json:"ci"`
- }
- type Cloud struct {
- ID string `json:"id" gorm:"primary_key"`
- Name string `json:"name"`
- }
- type Cluster struct {
- ID string `json:"id" gorm:"primary_key"`
- CreatedAt time.Time `json:"-"`
- UpdatedAt time.Time `json:"-"`
- ApplicationID string `json:"application_id"`
- VPCID string `json:"vpc_id"`
- Name string `json:"name"`
- ServiceAcctToken string `json:"service_acct_token"`
- ClusterHostname string `json:"cluster_hostname"`
- DashboardHostname string `json:"dashboard_hostname"`
- }
- type ClusterRole struct {
- ID string `json:"id" gorm:"primary_key"`
- CreatedAt time.Time `json:"-"`
- UpdatedAt time.Time `json:"-"`
- UserID string `json:"user_id"`
- ClusterID string `json:"cluster_id"`
- Type string `json:"admin" gorm:"user"`
- }
- type NamespaceRole struct {
- ID string `json:"id" gorm:"primary_key"`
- CreatedAt time.Time `json:"-"`
- UpdatedAt time.Time `json:"-"`
- UserID string `json:"user_id"`
- ClusterID string `json:"cluster_id"`
- NamespaceID string `json:"namespace_id"`
- Type string `json:"admin" gorm:"user"`
- }
- type Namespace struct {
- ID string `json:"id" gorm:"primary_key"`
- CreatedAt time.Time `json:"-"`
- UpdatedAt time.Time `json:"-"`
- ClusterID string `json:"cluster_id"`
- Name string `json:"name"`
- }
- type Session struct {
- ID string `json:"id" gorm:"primary_key"`
- CreatedAt time.Time `json:"-"`
- Token string `json:"token"`
- }
- type Token struct {
- ID string `json:"id" gorm:"primary_key"`
- CreatedAt time.Time `json:"-"`
- UpdatedAt time.Time `json:"-"`
- ClusterID string `json:"cluster_id"`
- UserID string `json:"user_id"`
- }
- type User struct {
- ID string `json:"id" gorm:"primary_key"`
- CreatedAt time.Time `json:"-"`
- UpdatedAt time.Time `json:"-"`
- SSO string `json:"sso"`
- FirstName string `json:"first_name"`
- LastName string `json:"last_name"`
- Email string `json:"email"`
- }
- type Vpc struct {
- ID string `json:"id" gorm:"primary_key"`
- CloudID string `json:"cloud_id"`
- Name string `json:"name"`
- }
- if !api.Database.HasTable(&Application{}) {
- api.Database.CreateTable(&Application{})
- }
- if !api.Database.HasTable(&Cloud{}) {
- api.Database.CreateTable(&Cloud{})
- }
- if !api.Database.HasTable(&Cluster{}) {
- api.Database.CreateTable(&Cluster{})
- }
- if !api.Database.HasTable(&ClusterRole{}) {
- api.Database.CreateTable(&ClusterRole{})
- }
- if !api.Database.HasTable(&NamespaceRole{}) {
- api.Database.CreateTable(&NamespaceRole{})
- }
- if !api.Database.HasTable(&Namespace{}) {
- api.Database.CreateTable(&Namespace{})
- }
- if !api.Database.HasTable(&Session{}) {
- api.Database.CreateTable(&Session{})
- }
- if !api.Database.HasTable(&Token{}) {
- api.Database.CreateTable(&Token{})
- }
- if !api.Database.HasTable(&User{}) {
- api.Database.CreateTable(&User{})
- }
- if !api.Database.HasTable(&Vpc{}) {
- api.Database.CreateTable(&Vpc{})
- }
- fmt.Println("Tables are created")
- // Initialize Router
- api.Router = mux.NewRouter()
- api.Router.HandleFunc("/api/v1/applications", api.handleApplications)
- api.Router.HandleFunc("/api/v1/application/{id}", api.handleApplication)
- api.Router.HandleFunc("/api/v1/applications", api.getApplications).Methods("GET")
- api.Router.HandleFunc("/api/v1/application", api.createApplication).Methods("POST")
- // api.Router.HandleFunc("/api/v1/application/{id:[0-9]+}", api.getApplication).Methods("GET")
- api.Router.HandleFunc("/api/v1/application/{id:[0-9]+}", api.updateApplication).Methods("PUT")
- api.Router.HandleFunc("/api/v1/application/{id:[0-9]+}", api.deleteApplication).Methods("DELETE")
- }
- func getApplications(db *gorm.DB, start, count int) ([]API, error) {
- return nil, errors.New("Not implemented")
- }
- func (api *API) getApplications(w http.ResponseWriter, r *http.Request) {
- count, _ := strconv.Atoi(r.FormValue("count"))
- start, _ := strconv.Atoi(r.FormValue("start"))
- if count > 10 || count < 1 {
- count = 10
- }
- if start < 0 {
- start = 0
- }
- applications, err := getApplications(api.Database, start, count)
- if err != nil {
- respondWithError(w, http.StatusInternalServerError, err.Error())
- return
- }
- respondWithJSON(w, http.StatusOK, applications)
- }
- func (api *API) createApplication(w http.ResponseWriter, r *http.Request) {
- count, _ := strconv.Atoi(r.FormValue("count"))
- start, _ := strconv.Atoi(r.FormValue("start"))
- type Application struct {
- ID string `json:"id" gorm:"primary_key"`
- AccessId int64
- CreatedAt time.Time `json:"-"`
- UpdatedAt time.Time `json:"-"`
- Name string `json:"name"`
- Ci string `json:"ci"`
- }
- app := Application{}
- decoder := json.NewDecoder(r.Body)
- if err := decoder.Decode(&app); err != nil {
- respondWithError(w, http.StatusBadRequest, "Invalid request payload")
- return
- }
- defer r.Body.Close()
- if err := app.createApplication(api.Database); err != nil {
- respondWithError(w, http.StatusInternalServerError, err.Error())
- return
- }
- respondWithJSON(w, http.StatusCreated, app)
- }
- func (api *API) getApplication(w http.ResponseWriter, r *http.Request) {
- type Application struct {
- ID string `json:"id" gorm:"primary_key"`
- AccessId int64
- CreatedAt time.Time `json:"-"`
- UpdatedAt time.Time `json:"-"`
- Name string `json:"name"`
- Ci string `json:"ci"`
- }
- vars := mux.Vars(r)
- app := Application{}
- id, err := strconv.Atoi(vars["id"])
- if err != nil {
- respondWithError(w, http.StatusBadRequest, "Invalid Application ID")
- return
- }
- if err := app.getApplication(api.Database); err != nil {
- switch err {
- case sql.ErrNoRows:
- respondWithError(w, http.StatusNotFound, "Application not found")
- default:
- respondWithError(w, http.StatusInternalServerError, err.Error())
- }
- return
- }
- respondWithJSON(w, http.StatusOK, app)
- }
- func (api *API) updateApplication(w http.ResponseWriter, r *http.Request) {
- app := models.Application{}
- vars := mux.Vars(r)
- id, err := strconv.Atoi(vars["id"])
- if err != nil {
- respondWithError(w, http.StatusBadRequest, "Invalid Application ID")
- return
- }
- decoder := json.NewDecoder(r.Body)
- if err := decoder.Decode(&app); err != nil {
- respondWithError(w, http.StatusBadRequest, "Invalid resquest payload")
- return
- }
- defer r.Body.Close()
- app.ID = ""
- if err := app.updateApplication(api.Database); err != nil {
- respondWithError(w, http.StatusInternalServerError, err.Error())
- return
- }
- respondWithJSON(w, http.StatusOK, app)
- }
- func (api *API) deleteApplication(w http.ResponseWriter, r *http.Request) {
- app := models.Application{}
- vars := mux.Vars(r)
- id, err := strconv.Atoi(vars["id"])
- if err != nil {
- respondWithError(w, http.StatusBadRequest, "Invalid Application ID")
- return
- }
- if err := app.deleteApplication(api.Database); err != nil {
- respondWithError(w, http.StatusInternalServerError, err.Error())
- return
- }
- respondWithJSON(w, http.StatusOK, map[string]string{"result": "success"})
- }
- func respondWithError(w http.ResponseWriter, code int, message string) {
- respondWithJSON(w, code, map[string]string{"error": message})
- }
- func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
- response, _ := json.Marshal(payload)
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(code)
- w.Write(response)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement