func BaseHandlers() *Handlers { lr := render.New(render.Options{ Layout: "layout", }) r := render.New(render.Options{}) return &Handlers{LayoutRender: lr, Render: r} }
// This function is called from main.go and from the tests // to create a new application. func NewApp(root string) *App { CheckEnv() // Use negroni for middleware ne := negroni.New() // Use gorilla/mux for routing ro := mux.NewRouter() // Use Render for template. Pass in path to templates folder // as well as asset helper functions. re := render.New(render.Options{ Directory: filepath.Join(root, "templates"), Layout: "layouts/layout", Extensions: []string{".html"}, Funcs: []template.FuncMap{ AssetHelpers(root), }, }) qre := render.New(render.Options{ Directory: filepath.Join(root, "templates"), Layout: "layouts/message", Extensions: []string{".html"}, Funcs: []template.FuncMap{ AssetHelpers(root), }, }) // Establish connection to DB as specificed in database.go db := NewDB() // Add middleware to the stack ne.Use(negroni.NewRecovery()) ne.Use(negroni.NewLogger()) ne.Use(NewAssetHeaders()) ne.Use(negroni.NewStatic(http.Dir("public"))) ne.UseHandler(ro) train.Config.SASS.DebugInfo = true train.Config.SASS.LineNumbers = true train.Config.Verbose = true train.Config.BundleAssets = true //ZZZtrain.ConfigureHttpHandler(ro) // Return a new App struct with all these things. return &App{ne, ro, re, qre, db} }
// CreateContact ... add new contact to a person func (c PersonController) CreateContact(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) { r := render.New(render.Options{}) contact := new(models.Contacts) errs := binding.Bind(req, contact) if errs.Handle(res) { r.JSON(res, 422, errs.Error()) return } bindingErr := contact.Validate(req, errs) if bindingErr != nil { r.JSON(res, 422, bindingErr.Error()) return } p := models.Contacts{ BaseModel: c.BaseModel, PhoneNo: contact.PhoneNo, PhoneNo2: contact.PhoneNo2, PhoneNo3: contact.PhoneNo3, Email: contact.Email, Website: contact.Website, FacebookID: contact.FacebookID, PersonID: contact.PersonID, CompanyEntitiesID: contact.CompanyEntitiesID} err := c.DataStore.SaveDatabaseObject(&p) if err != nil { panic(err) } // render response r.JSON(res, 200, p) }
func NewApp() *App { db := newDB() // Use negroni for middleware ne := negroni.New( negroni.NewRecovery(), negroni.NewLogger(), negroni.NewStatic(http.Dir("public")), ) // Use gorilla/mux for routing ro := mux.NewRouter() // Set StrictSlash to allow /things/ to automatically redirect to /things ro.StrictSlash(true) // Use Render for template. Pass in path to templates folder // as well as asset helper functions. re := render.New(render.Options{ Layout: "layouts/layout", Extensions: []string{".html"}, }) ne.UseHandler(ro) return &App{ne, ro, re, db} }
// CreatePersonIDType ... add new contact to a person func (c PersonController) CreatePersonIDType(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) { r := render.New(render.Options{}) personIDType := new(models.PersonIDType) errs := binding.Bind(req, personIDType) idTypes := models.IDType{} if errs.Handle(res) { r.JSON(res, 422, errs.Error()) return } bindingErr := personIDType.Validate(req, errs) if bindingErr != nil { r.JSON(res, 422, bindingErr.Error()) return } p := models.PersonIDType{ BaseModel: c.BaseModel, PersonID: personIDType.PersonID, IDType: personIDType.IDType, IDNumber: personIDType.IDNumber, DateIssued: personIDType.DateIssued, ExpiryDate: personIDType.ExpiryDate, ScannedPicture: personIDType.ScannedPicture, IDTypes: idTypes} err := c.DataStore.SaveDatabaseObject(&p) if err != nil { panic(err) } r.JSON(res, 200, p) }
func TestGetRandomMovie(t *testing.T) { s := &mockStore{} s.mockGetRandom = func() (*models.Movie, error) { return &models.Movie{ ImdbID: "tt090909090", Title: "The Martian", Actors: "Matt Damon", }, nil } c := AppConfig{ Store: s, Render: render.New(), Options: Options{}, } router := c.Router() r, err := http.NewRequest("GET", "/api/", nil) if err != nil { t.Fatal(err) } w := httptest.NewRecorder() router.ServeHTTP(w, r) if w.Code != http.StatusOK { t.Error("Should be a 200 OK") } }
//RegisterUser ... func (client *ClientController) RegisterUser(res http.ResponseWriter, req *http.Request) { //Extract the models from the request render := render.New(render.Options{}) registeredType := new(services.RegisteredUser) errs := binding.Bind(req, registeredType) userlogic.ServiceList = client.ServiceList userlogic.Logger = client.Logger if errs.Handle(res) { client.Logger.Crit(errs.Error()) render.JSON(res, 422, errs.Error()) return } bindingErr := registeredType.Validate(req, errs) if bindingErr != nil { client.Logger.Crit(bindingErr.Error()) render.JSON(res, 422, bindingErr.Error()) return } person, user, err := userlogic.RegisterUser(registeredType.Person, registeredType.User) if err != nil { client.Logger.Error(err.Error()) panic(err) } render.JSON(res, 200, map[string]interface{}{"Person": person, "User": user}) }
func main() { fmt.Println("jøkulhlaup ", Version) r := render.New(render.Options{}) m := martini.Classic() fizz := fizz.New() // Dashboard m.Get("/", func(w http.ResponseWriter, req *http.Request) { data := map[string]string{ "title": "Jøkulhlaup", "imgsrc": "img/jøkulhlaup.png", "width": "1440", "height": "900", } // !! Reload template !! //r = render.New(render.Options{}) // Render the specified templates/.tmpl file as HTML and return r.HTML(w, http.StatusOK, "black", data) }) // Activate the permission middleware m.Use(fizz.All()) // Share the files in static m.Use(martini.Static("static")) m.Run() // port 3000 by default }
// CreateAccount ... add new contact to a person func (acct AccountController) CreateAccount(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) { r := render.New(render.Options{}) account := new(models.Account) errs := binding.Bind(req, account) if errs.Handle(res) { r.JSON(res, 422, errs.Error()) return } bindingErr := account.Validate(req, errs) if bindingErr != nil { r.JSON(res, 422, bindingErr.Error()) return } p := models.Account{acct.BaseModel, account.AccountType, account.AccountNo, account.AccountCategoryID, account.AccountFundSource, account.AccountFundSourceID, account.AccountLimit, account.AccountLimitID, account.MaxBalance, account.MinBalance, account.CurrentBalance, account.CustomerID, account.Customer} //p := models.User{acct.BaseModel, user.Realm, user.Username, user.Password, user.Credential, user.Challenges, user.Email, user.Emailverified, user.Verificationtoken, // user.LogInCummulative, user.FailedAttemptedLogin, uuid.New(), user.PersonID, user.PhoneNum, user.VerifiedPhoneNum} err := acct.DataStore.SaveDatabaseObject(&p) if err != nil { panic(err) } // render response r.JSON(res, 200, p) }
// CreateAddress ... add new address to a person func (c PersonController) CreateAddress(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) { r := render.New(render.Options{}) address := new(models.Addresses) errs := binding.Bind(req, address) bs, _ := ioutil.ReadAll(req.Body) if errs.Handle(res) { c.Logger.Error(fmt.Sprintf("%s, %s", errs.Error(), string(bs))) r.JSON(res, 422, errs.Error()) return } bindingErr := address.Validate(req, errs) if bindingErr != nil { r.JSON(res, 422, bindingErr.Error()) return } p := &models.Addresses{ BaseModel: c.BaseModel, AddressType: address.AddressType, HouseNo: address.HouseNo, Street: address.Street, Area: address.Area, TownsID: address.TownsID, RegionStateID: address.RegionStateID, CountryID: address.CountryID, PersonID: address.PersonID, CompanyEntitiesID: address.CompanyEntitiesID} err := c.DataStore.SaveDatabaseObject(p) if err != nil { panic(err) } c.Logger.Info(fmt.Sprintf("%v", &p)) r.JSON(res, 200, p) }
// CreateCountry ... create new country func (c CommonController) CreateCountry(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) { r := render.New(render.Options{}) country := new(models.Country) errs := binding.Bind(req, country) if errs.Handle(res) { r.JSON(res, 422, errs.Error()) return } bindingErr := country.Validate(req, errs) if bindingErr != nil { r.JSON(res, 422, bindingErr.Error()) return } // save to database p := models.Country{c.BaseModel, country.ISOCode, country.Name, country.RegionStates, country.Language, country.LanguageID} err := c.DataStore.SaveDatabaseObject(&p) if err != nil { fmt.Println(err.Error()) panic(err) } else { r.JSON(res, 200, p) } // render response }
// CreateGood ... create new merchant func (mer MerchantController) CreateGood(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) { r := render.New(render.Options{}) good := new(models.Goods) errs := binding.Bind(req, good) if errs.Handle(res) { r.JSON(res, 422, errs.Error()) return } bindingErr := good.Validate(req, errs) if bindingErr != nil { r.JSON(res, 422, bindingErr.Error()) return } // save to database p := models.Goods{mer.BaseModel, good.MerchantID, good.PercentDiscount, good.AvailFrom, good.AvailTo, good.Promo, good.UnitPrice, good.GoodServices, good.GoodserviceID, good.GoodCategoryID, good.GoodHist} err := mer.DataStore.SaveDatabaseObject(&p) if err != nil { panic(err) } // render response r.JSON(res, 200, p) }
func Participate(config ConfigFactory, logger func(interface{})) func(http.ResponseWriter, *http.Request) { cfg := *config() return func(w http.ResponseWriter, req *http.Request) { r := render.New() if req.Method != "POST" { r.JSON(w, http.StatusMethodNotAllowed, "Method not supported") fmt.Errorf("ERROR: method not supported") return } preq := ParticipateRequest{} body, rerr := ioutil.ReadAll(req.Body) if rerr != nil { r.JSON(w, http.StatusBadRequest, fmt.Sprintf("Error reading body: %s", rerr)) fmt.Errorf("ERROR: reading body: %v", rerr) return } err := json.Unmarshal(body, &preq) if err != nil { r.JSON(w, http.StatusBadRequest, fmt.Sprintf("Error decoding json: %s", err)) fmt.Errorf("ERROR: decoding json: %s received: %s", err, string(body)) return } presp := new(ParticipateResponse) presp.Experiments = CheckExperiments(preq.Experiments, preq.Context.Uid, cfg) presp.Features = CheckFeatures(preq.Features, preq.Context.Uid, cfg) r.JSON(w, http.StatusOK, presp) go logger(*presp) } }
// CreateMerchant ... create new merchant func (mer MerchantController) CreateMerchant(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) { r := render.New(render.Options{}) merchant := new(models.Merchant) errs := binding.Bind(req, merchant) if errs.Handle(res) { r.JSON(res, 422, errs.Error()) return } bindingErr := merchant.Validate(req, errs) if bindingErr != nil { r.JSON(res, 422, bindingErr.Error()) return } // save to database p := models.Merchant{mer.BaseModel, merchant.Account, merchant.AccountID, merchant.Customer, merchant.CustomerID, merchant.AlternativeID, merchant.Goods} err := mer.DataStore.SaveDatabaseObject(&p) if err != nil { panic(err) } // render response r.JSON(res, 200, p) }
func RingApi(w http.ResponseWriter, r *http.Request, worker *Worker) { var ring interface{} u, _ := url.Parse(r.URL.String()) queryParams := u.Query() switch queryParams.Get("tracker") { case "snowplow": switch queryParams.Get("ring") { case "success": ring = worker.Stats.SnowplowSuccessRing.Display() case "failed": ring = worker.Stats.SnowplowFailRing.Display() } case "adjust": switch queryParams.Get("ring") { case "success": ring = worker.Stats.AdjustSuccessRing.Display() case "failed": ring = worker.Stats.AdjustFailRing.Display() } } rndr := render.New() b, err := json.MarshalIndent(ring, "", " ") if err != nil { rndr.Text(w, http.StatusBadRequest, "Cant draw pretty JSON") return } rndr.Text(w, http.StatusOK, string(b)) }
func StatusApi(w http.ResponseWriter, r *http.Request, worker *Worker) { rndr := render.New() stats := worker.Stats adjustSuccessRing := stats.AdjustSuccessRing.Display() adjustFailRing := stats.AdjustFailRing.Display() snowplowSuccessRing := stats.SnowplowSuccessRing.Display() snowplowFailRing := stats.SnowplowFailRing.Display() status := Status{ RabbitHealth: stats.RabbitHealth.Get(), PostgresHealth: stats.PostgresHealth.Get(), AdjustSuccess: adjustSuccessRing.Total, AdjustFailed: adjustFailRing.Total, SnowplowSuccess: snowplowSuccessRing.Total, SnowplowFailed: snowplowFailRing.Total, Uptime: time.Since(stats.StartTime).String(), } b, err := json.MarshalIndent(status, "", " ") if err != nil { rndr.Text(w, http.StatusBadRequest, "Cant draw pretty JSON") return } httpStatus := http.StatusOK if !status.RabbitHealth || !status.PostgresHealth { httpStatus = http.StatusTooManyRequests } rndr.Text(w, httpStatus, string(b)) }
func New(db *database.DB, mailer mailer.Mailer, log *logrus.Logger, cfg *config.Config) *Server { secureCookieKey, _ := base64.StdEncoding.DecodeString(cfg.SecureCookieKey) cookie := securecookie.New( []byte(cfg.SecretKey), secureCookieKey, ) renderOptions := render.Options{ IsDevelopment: cfg.IsDev(), } renderer := render.New(renderOptions) f := feedparser.New(db, log) return &Server{ DB: db, Config: cfg, Log: log, Render: renderer, Cookie: cookie, Feedparser: f, Mailer: mailer, } }
func LoadEnvironment(env string) (err error) { if !isValidEnvironment(env) { return fmt.Errorf("'%s' is not one of the supported enviroments: %v", env, strings.Join(Environments, ",")) } Env = env // Load environment variables envFileName := Env + ".env" if err = godotenv.Load(envFileName); err != nil { return } // Connect to database if err = connectDB(); err != nil { return } // Initialize render Render = render.New(render.Options{ Directory: "templates", Layout: "", Delims: render.Delims{Left: "{{%", Right: "%}}"}, Extensions: []string{".tmpl", ".html"}, IsDevelopment: Env == EnvDevelopment, }) return }
// CreateLanguage ... create new language func (c CommonController) CreateLanguage(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) { r := render.New(render.Options{}) language := new(models.Language) errs := binding.Bind(req, language) if errs.Handle(res) { r.JSON(res, 422, errs.Error()) return } bindingErr := language.Validate(req, errs) if bindingErr != nil { r.JSON(res, 422, bindingErr.Error()) return } // save to database p := models.Language{c.BaseModel, language.ISOCode, language.Name} err := c.DataStore.SaveDatabaseObject(&p) if err != nil { panic(err) } // render response r.JSON(res, 200, p) }
func GetNodeInfo(res http.ResponseWriter, req *http.Request) { r := render.New() vars := mux.Vars(req) node := vars["node"] if node == "" { r.JSON(res, http.StatusInternalServerError, "No node name provided") return } sets, err := Resolv(node) if err != nil { r.JSON(res, http.StatusNotFound, "Node could not be resolved") return } for _, s := range sets { for _, n := range networks { if n.Contains(s.Addr) { r.JSON(res, http.StatusOK, n) return } } } r.JSON(res, http.StatusNotFound, "No matching network found") }
// CreateRegion ... create new region func (c CommonController) CreateRegion(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) { r := render.New(render.Options{}) region := new(models.RegionState) errs := binding.Bind(req, region) if errs.Handle(res) { r.JSON(res, 422, errs.Error()) return } bindingErr := region.Validate(req, errs) if bindingErr != nil { r.JSON(res, 422, bindingErr.Error()) return } // save to database p := models.RegionState{c.BaseModel, region.Name, region.CountryID, region.Towns} err := c.DataStore.SaveDatabaseObject(&p) if err != nil { panic(err) } // render response r.JSON(res, 200, p) }
func GetNetworkIps(res http.ResponseWriter, req *http.Request) { r := render.New() vars := mux.Vars(req) network_name := vars["net"] if network_name == "" { r.JSON(res, http.StatusInternalServerError, "No network name provided") return } for _, network := range networks { if network.Name == network_name { ips, err := network.ExpandDetailed() if err != nil { r.JSON(res, http.StatusInternalServerError, "Network could not be expanded") return } c := NewCheck(ips) c.Run() network.Utilization = c.utilization var out []*ResultSet for _, elem := range c.results { out = append(out, elem) } r.JSON(res, http.StatusOK, out) return } } r.JSON(res, http.StatusNotFound, "No matching network found") }
// CreateCustomer ... Add new customer func (acct AccountController) CreateCustomer(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) { r := render.New(render.Options{}) customer := new(models.Customer) errs := binding.Bind(req, customer) if errs.Handle(res) { r.JSON(res, 422, errs.Error()) return } bindingErr := customer.Validate(req, errs) if bindingErr != nil { r.JSON(res, 422, bindingErr.Error()) return } p := models.Customer{acct.BaseModel, customer.Person, customer.PersonID, customer.CompanyEntites, customer.CompanyEntitesID, customer.CustomerType, customer.CustomerTypeID} //p := models.User{acct.BaseModel, user.Realm, user.Username, user.Password, user.Credential, user.Challenges, user.Email, user.Emailverified, user.Verificationtoken, // user.LogInCummulative, user.FailedAttemptedLogin, uuid.New(), user.PersonID, user.PhoneNum, user.VerifiedPhoneNum} err := acct.DataStore.SaveDatabaseObject(&p) if err != nil { panic(err) } // render response r.JSON(res, 200, p) }
func main() { // Render engine r := render.New(render.Options{ Layout: "layout", }) // Handlers router := mux.NewRouter() router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { r.HTML(w, http.StatusOK, "home", nil) }) router.HandleFunc("/about", func(w http.ResponseWriter, req *http.Request) { r.HTML(w, http.StatusOK, "about", nil) }) router.HandleFunc("/start", func(w http.ResponseWriter, req *http.Request) { time := req.FormValue("time") stepsPerMinute, _ := strconv.Atoi(req.FormValue("steps")) var hours, minutes, seconds int fmt.Sscanf(time, "%d:%d:%d", &hours, &minutes, &seconds) fmt.Println(hours, minutes, seconds) go startLapse((hours*3600)+(minutes*60)+seconds, stepsPerMinute) r.HTML(w, http.StatusOK, "home", nil) }).Methods("POST") // HTTP Server n := negroni.Classic() n.UseHandler(router) n.Run(":3000") }
// New returns a new blank Engine instance with no middleware attached func New(opts Options) *Engine { namespace := opts.Namespace if len(namespace) == 0 { namespace = "/" } engine := &Engine{} engine.Router = &Router{ namespace: namespace, engine: engine, mux: chi.NewRouter(), } engine.options = opts engine.pool.New = func() interface{} { ctx := &Context{ Engine: engine, render: render.New(render.Options{ Layout: "layout", }), } return ctx } return engine }
// Init :init controller methods func init() { Render = render.New(render.Options{ Directory: "templates", Layout: "layout", }) RedisPool = newRedisPool() }
//AddNewAddressToUser ... Add address to a user profile func (client *ClientController) AddNewAddressToUser(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) { render := render.New(render.Options{}) address := models.Addresses{} errs := binding.Bind(req, &address) userlogic.ServiceList = client.ServiceList userlogic.Logger = client.Logger userlogic.AuthorizationToken = req.Header.Get("Authorization") if errs.Handle(res) { client.Logger.Crit(errs.Error()) render.JSON(res, 422, errs.Error()) return } bindingErr := address.Validate(req, errs) if bindingErr != nil { client.Logger.Crit(bindingErr.Error()) render.JSON(res, 422, bindingErr.Error()) return } savedEntity, bSave, err := userlogic.AddNewAddressToUser(address) if !bSave && err != nil { client.Logger.Error(err.Error()) panic(err) } render.JSON(res, 200, savedEntity) }
func InjectRender(c *web.C, h http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { c.Env["render"] = render.New(render.Options{ Directory: "views", Layout: "", Extensions: []string{".tmpl"}, Funcs: []template.FuncMap{template.FuncMap{ "classIfHere": func(path, class string) template.HTMLAttr { if r.URL.Path == path { return template.HTMLAttr(fmt.Sprintf(`class="%s"`, class)) } return template.HTMLAttr("") }, "date": func(date time.Time) string { return date.Format("January 2, 2006") }, "checkIfInArray": func(x string, slice []string) template.HTMLAttr { for _, y := range slice { if x == y { return template.HTMLAttr("checked") } } return template.HTMLAttr("") }, }}, }) h.ServeHTTP(w, r) } return http.HandlerFunc(fn) }
func indexHandler(c web.C, w http.ResponseWriter, r *http.Request) { ren := render.New(render.Options{ Layout: "layout", Extensions: []string{".html"}, }) ren.HTML(w, http.StatusOK, "index", nil) }
func main() { render := render.New(render.Options{ Directory: "src/views", Extensions: []string{".html"}, }) http.HandleFunc("/img/", serveResource) http.HandleFunc("/css/", serveResource) http.HandleFunc("/js/", serveResource) goji.Get("/hello/:name", func(c web.C, w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, %s!", c.URLParams["name"]) }) goji.Get("/wow", func(c web.C, w http.ResponseWriter, r *http.Request) { render.HTML(w, http.StatusOK, "index", nil) }) goji.Get("/bar", func(c web.C, w http.ResponseWriter, r *http.Request) { render.HTML(w, http.StatusOK, "bar", nil) }) goji.Get("/", func(c web.C, w http.ResponseWriter, r *http.Request) { render.HTML(w, http.StatusOK, "index", nil) }) goji.Serve() }