// NewWebServer : create and configure a new web server func NewWebServer(c *Config, l *Store, level int) *WebHandler { wh := &WebHandler{} // create the router if level == 0 { gin.SetMode(gin.ReleaseMode) wh.router = gin.New() } if level == 1 { gin.SetMode(gin.ReleaseMode) wh.router = gin.Default() } if level > 1 { wh.router = gin.Default() } // bind the lease db wh.store = l // bind the config wh.config = c // bind the config to the file store wh.fs = c.fs // templates // base os selector t, err := template.New("list").Parse(OsSelector) if err != nil { logger.Critical("template error : %v", err) return nil } // class selector _, err = t.New("class").Parse(ClassSelector) if err != nil { logger.Critical("template error : %v", err) return nil } wh.templates = t // rocket handlers wh.RocketHandler() // chose and operating system wh.router.GET("/choose", wh.Lister) wh.router.GET("/choose/:dist/:mac", wh.Chooser) wh.router.GET("/class/:dist/:mac", wh.ClassChooser) wh.router.GET("/setclass/:dist/:class/:mac", wh.ClassSet) // get the boot line for your operating system wh.router.GET("/boot/:dist/:mac", wh.Starter) // load the kernel and file system wh.router.GET("/image/:dist/*path", wh.Images) // serve the bin folder wh.router.GET("/bin/*path", wh.Binaries) // actions for each distro wh.router.GET("/action/:dist/:action", wh.Action) // configs for each distro wh.router.GET("/config/:dist/:action", wh.Config) if wh.config.Spawn { wh.SpawnHandler() } return wh }
func main() { port := flag.Int("port", 8080, "port") backends := flag.String("workers", "", "knonw workers (ex: 'localhost:8081,localhost:8082')") strategy := flag.String("strategy", "majority", "balancing strategy ['one', 'two', 'majority', 'all']") poolSize := flag.Int("pool", 3, "size of the pool of available worker sets") flag.Parse() cfg := profile.Config{ CPUProfile: true, MemProfile: true, ProfilePath: ".", } p := profile.Start(&cfg) defer p.Stop() proxy := Proxy{NewBalancer(initListOfBckends(backends), strategy, poolSize)} server := gin.Default() server.GET("/", func(c *gin.Context) { pipes := &Pipes{ Done: make(chan struct{}), Result: make(chan *DataFormat), } go proxy.ProcessFirstResponse(pipes) defer close(pipes.Done) select { case data := <-pipes.Result: c.JSON(200, data) case <-time.After(globalTimeout): c.JSON(500, nil) } }) go func() { admin := gin.Default() admin.POST("/worker/*endpoint", func(c *gin.Context) { worker := c.Param("endpoint") done := make(chan struct{}) go proxy.AddBackend(fmt.Sprintf("http:/%s/", worker), done) select { case <-done: c.String(200, "") case <-time.After(globalTimeout): c.String(500, "") close(done) } }) admin.Run(fmt.Sprintf(":%d", *port-10)) }() server.Run(fmt.Sprintf(":%d", *port)) }
func runHttpServer() { router := gin.Default() router.GET("/", handleGetServices) router.GET("/services", handleGetServices) router.GET("/services/:name", handleGetService) router.Run("0.0.0.0:5000") }
func main() { // fire this up router := gin.Default() router.Use(gin.Logger()) // load the dang templates router.LoadHTMLGlob("templates/*.html") // router.Use(static.Serve("/static", static.LocalFile("html", false))) router.Static("/static", "static") // handle root router.GET("/", func(c *gin.Context) { c.String(http.StatusOK, "wat") }) // check the incoming phrase router.GET("/blink/:phrase", func(c *gin.Context) { phrase := c.Param("phrase") c.HTML(http.StatusOK, "main.html", gin.H{ "title": phrase, "phrase": phrase, "twitter_handle": "mike_dory", "google_analytics_id": "XXXXX-XX", }) }) // run! router.Run(":8081") }
func setup() { database.Open("testing.db") timeStamp, _ := time.Parse(time.RFC3339Nano, "2015-11-19T12:19:33.865042825+01:00") items := []*model.Item{ &model.Item{ Code: "url", Type: model.URLItemType, Content: "https://ariejan.net", CreatedAt: timeStamp, }, &model.Item{ Code: "txt", Type: model.TextItemType, Content: "Lorem ipsum", CreatedAt: timeStamp, }, } for _, item := range items { database.SaveItem(item) } router = gin.Default() web.Setup(router.Group("/"), database) }
func main() { //move this into an env dsn := "homestead:secret@tcp(localhost:33060)/wheniwork?charset=utf8&parseTime=True&loc=Local" repository, err := wiw.NewMySQLRepo(dsn) if err != nil { log.Println("ERROR: Cannot build repository") log.Println(err) log.Fatal("Exiting...") return } router := gin.Default() schedulerAPI := schedulerService{repository} authMiddleware := router.Group("/", schedulerAPI.Authorization) setIDMiddleware := authMiddleware.Group("/", schedulerAPI.ValidateID) authMiddleware.POST("/shifts/", schedulerAPI.CreateOrUpdateShift) setIDMiddleware.PUT("/shifts/:id", schedulerAPI.CreateOrUpdateShift) authMiddleware.GET("/shifts/", schedulerAPI.ViewShiftsByDate) setIDMiddleware.GET("/users/:id/shifts/", schedulerAPI.ViewShiftsForUser) setIDMiddleware.GET("/users/:id/colleagues/", schedulerAPI.ViewColleagues) setIDMiddleware.GET("/users/:id/managers", schedulerAPI.ViewManagers) setIDMiddleware.GET("/users/:id", schedulerAPI.ViewUser) router.Run(":3001") }
// Run runs the app func (app *Application) Run() error { r := gin.Default() r.LoadHTMLGlob("templates/*") // inject Config into context r.Use(func(c *gin.Context) { c.Set("cfg", app.Config) c.Next() }) // CSRF r.Use(wraphh.WrapHH(nosurf.NewPure)) r.Static(app.Options.StaticURL, app.Options.StaticDir) r.GET("/", indexPage) api := r.Group("/api") api.GET("/all/", getMovies) api.GET("/", getRandomMovie) api.POST("/", addMovie) api.GET("/suggest", suggest) api.GET("/movie/:id", getMovie) api.DELETE("/movie/:id", deleteMovie) api.PATCH("/seen/:id", markSeen) r.Run() return nil }
func main() { // prepare host:port to listen to bind := fmt.Sprintf("%s:%s", "", "8000") // just predefine the err variable to avoid some problems var err error // create an instance of Telegram Bot Api bot, err = telegram.NewBotAPI(BOTAPIKEY) if err != nil { log.Panic(err) } // Compile the regexpression to match /action@botname actionSeprator := regexp.MustCompile(`^\/[\da-zA-z@]+`) // prepare the Gin Router router := gin.Default() // on request router.POST("/", func(c *gin.Context) { buf, err := ioutil.ReadAll(c.Request.Body) update := telegram.Update{} json.Unmarshal(buf, &update) if err != nil { c.String(500, err.Error()) return } // Extracting action name from text botName := "" act := actionSeprator.FindString(update.Message.Text) actLength := len(act) atsignPos := strings.Index(act, "@") if atsignPos != -1 { botName = act[atsignPos+1:] act = act[:atsignPos] } if botName != "" && botName != BOTNAME { c.String(200, "Wrong bot") return } act = strings.TrimPrefix(act, "/") act = strings.ToLower(act) update.Message.Text = update.Message.Text[actLength:] // check if the requested action exist or not _, has := actions[act] if has { err = actions[act](c, &update) if err != nil { c.String(500, err.Error()) return } } c.String(200, "done") }) router.Run(bind) }
func main() { r := gin.Default() r.GET("/long_async", func(c *gin.Context) { // create copy to be used inside the goroutine cCp := c.Copy() go func() { // simulate a long task with time.Sleep(). 5 seconds time.Sleep(5 * time.Second) // note than you are using the copied context "c_cp", IMPORTANT log.Println("Done! in path " + cCp.Request.URL.Path) }() }) r.GET("/long_sync", func(c *gin.Context) { // simulate a long task with time.Sleep(). 5 seconds time.Sleep(5 * time.Second) // since we are NOT using a goroutine, we do not have to copy the context log.Println("Done! in path " + c.Request.URL.Path) }) // Listen and server on 0.0.0.0:8080 r.Run(":8080") }
func route() { // If we're in production mode don't run gin in develop if *production { gin.SetMode(gin.ReleaseMode) } // Create new router router = gin.Default() // Compile html templates router.LoadHTMLGlob("app/html/*.html") // Add all routes addRoutes() // Add static routes router.Static("/", "./public/") // Create http server based off of net/http addr := fmt.Sprintf("%s:%d", *host, *port) s := &http.Server{ Addr: addr, Handler: router, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } // Log log.Fatal(s.ListenAndServe()) }
func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) r.Run(":3000") }
func main() { router := gin.Default() usf4Map := TitleMap{name: "usf4", characterMap: BuildData("usf4")} router.GET("/:title/:name", func(context *gin.Context) { switch title := context.Param("title"); title { case "usf4": name := context.Param("name") if strings.EqualFold(name, "characters") { context.JSON(200, gin.H{ "names": CharacterNames(title), }) } else { character, characterFound := usf4Map.characterMap[name] if !characterFound { context.JSON(404, gin.H{ "message": "character not found", }) } context.String(200, character.data) } case "sfv": context.JSON(501, gin.H{ "message": "coming soon", }) default: context.JSON(404, gin.H{ "message": "title not found", }) } }) router.Run(":8080") }
func main() { r := gin.Default() g := r.Group("/i", func(c *gin.Context) { c.Header("Cache-Control", "max-age=315360000") }) g.GET("/g/:name", func(c *gin.Context) { name := c.Param("name") queryWidth := c.DefaultQuery("w", "512") queryMargin := c.DefaultQuery("m", "32") width, err := strconv.Atoi(queryWidth) margin, err2 := strconv.Atoi(queryMargin) if err != nil || err2 != nil { log.Println(err, err2) c.AbortWithError(http.StatusInternalServerError, errors.New("Invalid parameters")) return } GenerateGitHub(c, name, width, margin) }) g.GET("/8/:gender/:name", Generate8bit) port := os.Getenv("PORT") if port == "" { port = "8080" } r.Run(":" + port) }
func main() { mux := http.NewServeMux() Admin.MountTo("/admin", mux) // frontend routes router := gin.Default() router.LoadHTMLGlob("templates/*") // serve static files router.StaticFS("/system/", http.Dir("public/system")) router.StaticFS("/assets/", http.Dir("public/assets")) // books bookRoutes := router.Group("/books") { // listing bookRoutes.GET("", controllers.ListBooksHandler) bookRoutes.GET("/", controllers.ListBooksHandler) // really? i need both of those?... // single book - product page bookRoutes.GET("/:id", controllers.ViewBookHandler) } mux.Handle("/", router) // handle login and logout of users mux.HandleFunc("/login", controllers.LoginHandler) mux.HandleFunc("/logout", controllers.LogoutHandler) // start the server http.ListenAndServe(":9000", mux) }
func Init() { if router == nil { gin.SetMode(gin.TestMode) router = gin.Default() templ := template.New("index") router.SetHTMLTemplate(templ) store := sessions.NewCookieStore([]byte("foundation")) router.Use(sessions.Sessions("foundation", store)) portNo := 0 go func() { router.GET("/", func(c *gin.Context) { shared = *c }) for portNo = 8124; true; portNo++ { addr := fmt.Sprintf(`:%d`, portNo) err := router.Run(addr) if err != nil { if strings.HasSuffix(err.Error(), `address already in use`) { continue } } break } }() time.Sleep(50 * time.Millisecond) http.Get(fmt.Sprintf("http://localhost:%d/", portNo)) // portNoが0じゃなくなるまでwaitしたほうが良い気もするが一旦 } }
func main() { gin.SetMode(gin.ReleaseMode) r := gin.Default() sigc := make(chan os.Signal, 1) signal.Notify(sigc, syscall.SIGHUP) go func() { <-sigc config = loadConfig(configFile) log.Println("config reloaded") }() config := loadConfig("config.json") r.POST("/", func(c *gin.Context) { var json Webhook if c.BindJSON(&json) == nil { processWebhook(json) c.String(http.StatusOK, "Ok.") } else { c.String(401, "Nope.") } }) address := config.Address + ":" + strconv.FormatInt(config.Port, 10) r.Run(address) }
func main() { r := gin.Default() r.Static("/estatico", "estatico/") r.LoadHTMLGlob("templates/*") r.GET("/", func(c *gin.Context) { go demorado() c.HTML(http.StatusOK, "ola.html", gin.H{ "msg": "Bem-vindo!", }) }) r.GET("/dados", func(c *gin.Context) { c.JSON(http.StatusOK, struct { Mensagem string `json:"msg"` }{"Oláaaaaaaaaa, enfermeira!"}, ) }) r.Run(":8080") }
func main() { web := gin.Default() web.Static("/static", "./assets") web.StaticFile("/", "./assets/index.html") web.GET("/rss/:user/:hash", func(c *gin.Context) { userID := c.Param("user") hash := c.Param("hash") ifNoneMatch := c.Request.Header.Get("If-None-Match") i := newInstapaper(userID, hash) err := i.fetchInstapaperFeed(ifNoneMatch) if err != nil { log.Println(err) c.XML(http.StatusBadRequest, nil) return } if i.notModified { c.Header("Etag", i.etag) c.XML(http.StatusNotModified, nil) return } feed := feedFromInstapaper(i.feed) c.XML(http.StatusOK, feed) }) web.GET("/proxy/:scheme/:host/*path", func(c *gin.Context) { scheme := c.Param("scheme") host := c.Param("host") path := c.Param("path") query := c.Request.URL.Query().Encode() u := url.URL{Scheme: scheme, Host: host, Path: path, RawQuery: query} article, err := extractFromURL(u) if err != nil { log.Println(err) c.String(http.StatusInternalServerError, "") return } audioBuffer, err := speak(article) if err != nil { log.Println(err) c.String(http.StatusInternalServerError, "") return } err = audioBuffer.WriteTo(c.Writer) if err != nil { log.Println(err) } }) web.Run(":3000") }
func main() { port := flag.Int("port", 8080, "port") backends := flag.Int("workers", 3, "number of workers") strategy := flag.String("strategy", "majority", "balancing strategy ['one', 'two', 'majority', 'all']") flag.Parse() cfg := profile.Config{ CPUProfile: true, MemProfile: true, ProfilePath: ".", } p := profile.Start(&cfg) defer p.Stop() balancer := newBalancer(backends, strategy) a := gin.Default() a.GET("/", func(c *gin.Context) { timeouted := make(chan bool) result := processFirstResponse(timeouted, balancer) select { case data := <-result: c.JSON(200, data) case <-time.After(globalTimeout): c.JSON(500, nil) timeouted <- true } }) a.Run(fmt.Sprintf(":%d", *port)) }
func main() { cfg, err := ini.Load("config.ini") if err != nil { log.Printf("dude wtf %v\n", err) return } sec := cfg.Section("") hostname := sec.Key("LISTEN_TO_IP").MustString("") + ":" + sec.Key("LISTEN_TO_PORT").MustString("8080") AdminPassword = sec.Key("ADMIN_PASSWORD").MustString("") IsRemote = sec.Key("IS_REMOTE").MustBool(false) if !GenerateVideoCache() { return } go SleepRegenerate() r := gin.Default() r.LoadHTMLGlob("templates/*") r.Static("/assets", "./public") r.Static("/video", "./video") r.GET("/", GetHome) r.GET("/list", GetList) api := r.Group("/api") { api.GET("/list", GetAPIList) api.GET("/details", GetAPIDetails) api.GET("/list.php", GetAPIList) api.GET("/details.php", GetAPIDetails) api.GET("/refresh_video_cache", GetAPIRefreshVideoCache) } r.NoRoute(NotFound) r.Run(hostname) }
func main() { r = gin.Default() // Global middleware r.Use(gin.Logger()) r.Use(gin.Recovery()) r.Static("/assets", "./assets") r.LoadHTMLGlob("view/*") // Simple group: v1 v1 := r.Group("/") { v1.GET("/", home.Dispatch) } // Simple group: v2 v2 := r.Group("/api") { v2.GET("/login", api.Login) v2.GET("/mail/list", api.MailList) v2.GET("/mail/detail", api.MailDetail) v2.GET("/mail/box", api.MailBox) v2.GET("/mail/send", api.MailSend) v2.GET("/mail/set", api.MailSet) } r.Run(":8081") }
func main() { flag.Parse() //redisPool := redis.NewPool(func()(redis.Conn, error) { //c, err := redis.Dial("tcp", *redisAddress) // //if err != nil { //return nil, err //} //return c, err //}, *maxConnections) // //defer redisPool.close() conn, err := redis.Dial("tcp", ":6379") if err != nil { fmt.Println("err") return } conn.Do("SET", "Michael", "Cool") defer conn.Close() r := gin.Default() r.GET("/ping", func(c *gin.Context) { s, _ := redis.String(conn.Do("GET", "Michael")) c.String(200, s) }) r.Run(":8080") }
func main() { router := gin.Default() // just the ping api router.GET("/", func(c *gin.Context) { c.String(200, "OK") }) router.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) router.GET("/_ping", func(c *gin.Context) { c.String(200, "pong") }) // consume 256KB memory immediately, // and release the memory after 10s router.GET("/memory", AllocateQuotaMemory) // comsume :size memory of server // unit is MB router.GET("/memory/:size/action/allocate", AllocateCustomMemory) // consume as much cpu as it can router.GET("/cpu", ConsumeCPU) router.Run(":8080") }
func main() { net := NewGreetingFlow() in := make(chan string) out := make(chan string) net.SetInPort("In", in) net.SetOutPort("Out", out) flow.RunNet(net) router := gin.Default() router.GET("/:name", func(c *gin.Context) { name := c.Params.ByName("name") in <- name var resp struct { Title string `json:"greeter"` Value string } resp.Title = "golang" resp.Value = <-out c.JSON(200, resp) }) router.Run(":8080") close(in) close(out) <-net.Wait() }
func Test(t *testing.T) { respMap := map[string]string{"hello": "world"} respJson, _ := json.Marshal(respMap) handler := func(wr http.ResponseWriter, req *http.Request) { wr.WriteHeader(http.StatusOK) fmt.Fprint(wr, string(respJson)) } mux := http.NewServeMux() mux.HandleFunc("/hello", handler) router := gin.Default() ginHandler := func(ctx *gin.Context) { ctx.JSON(http.StatusOK, gin.H{"hello": "world"}) } ginHandler2 := func(ctx *gin.Context) { ctx.String(http.StatusOK, string("xx")) } router.GET("/hello/:id", ginHandler) router.GET("/hellos", ginHandler2) httpmock.ListenAndServe("hello.com", router) response := httpmock.GET("/hello/1", nil) AssertResponseEqual(t, response, `{"hello":"world"}`) AssertEqual(t, response.Code, http.StatusOK) }
func main() { fmt.Println("Monitor Service starting...") r := gin.Default() r.Use(static.Serve("/", static.LocalFile("static", true))) r.GET("/api/GetServerGroups", func(c *gin.Context) { groups, err := ReadData() if err == nil { groups = FillPublishInfo(groups) // Get publish info c.JSON(200, groups) } else { c.String(500, "ReadData error: "+err.Error()) } }) r.POST("/api/SaveServer", func(c *gin.Context) { var s Server if err := c.BindJSON(&s); err == nil { UpdateData(s) c.String(200, "OK") } else { c.String(500, "BindJSON error: "+err.Error()) } }) fmt.Println("Monitor Service started!") r.Run(":8080") }
func main() { file := "file.txt" r := gin.Default() m := melody.New() w, _ := fsnotify.NewWatcher() r.GET("/", func(c *gin.Context) { http.ServeFile(c.Writer, c.Request, "index.html") }) r.GET("/ws", func(c *gin.Context) { m.HandleRequest(c.Writer, c.Request) }) m.HandleConnect(func(s *melody.Session) { content, _ := ioutil.ReadFile(file) s.Write(content) }) go func() { for { ev := <-w.Events if ev.Op == fsnotify.Write { content, _ := ioutil.ReadFile(ev.Name) m.Broadcast(content) } } }() w.Add(file) r.Run(":5000") }
func (profileService *ProfileService) Run(cfg Config) error { router := gin.Default() session, err := mgo.Dial("localhost") if err != nil { panic(err) } defer session.Close() // Optional. Switch the session to a monotonic behavior. session.SetMode(mgo.Monotonic, true) col := session.DB(DBNAME).C(COL_PROFILE) pr := &ProfileResource{col: col} router.GET("/ping", func(c *gin.Context) { c.String(200, "Profile Service is Available") }) router.POST("/api/profiles", pr.CreateProfile) router.POST("/api/authuser", pr.FindUserByEmailPass) router.Run(":8089") return nil }
func startApp(db *gorm.DB) { log := logging.MustGetLogger("log") if viper.GetString("logtype") != "debug" { gin.SetMode(gin.ReleaseMode) } g := gin.Default() //r := NewRessource(db) g.Use(cors.Middleware(cors.Config{ Origins: "*", Methods: "GET, PUT, POST, DELETE", RequestHeaders: "Origin, Authorization, Content-Type", ExposedHeaders: "", MaxAge: 50 * time.Second, Credentials: true, ValidateHeaders: false, })) g.Static("/", "./static") /*v1 := g.Group("api/v1") { v1.GET("/temperatures", r.GetTemperatures) v1.POST("/temperature", r.PostTemperature) }*/ log.Debug("Port: %d", viper.GetInt("server.port")) g.Run(":" + strconv.Itoa(viper.GetInt("server.port"))) }
func main() { r := gin.Default() r.Static("/assets", "assets") store := sessions.NewCookieStore([]byte("gssecret")) r.Use(sessions.Sessions("mysession", store)) r.LoadHTMLGlob("templates/*") fc := new(FrontController) r.GET("/", fc.HomeCtr) r.GET("/about", fc.AboutCtr) r.GET("/view/:id", fc.ViewCtr) r.GET("/view.php", fc.ViewAltCtr) r.GET("/ping", fc.PingCtr) r.GET("/search", fc.SearchCtr) ac := new(AdminController) admin := r.Group("/admin") { admin.GET("/", ac.ListBlogCtr) admin.GET("/login", ac.LoginCtr) admin.POST("/login-process", ac.LoginProcessCtr) admin.GET("/logout", ac.LogoutCtr) admin.GET("/addblog", ac.AddBlogCtr) admin.POST("/save-blog-add", ac.SaveBlogAddCtr) admin.GET("/listblog", ac.ListBlogCtr) admin.GET("/deleteblog/:id", ac.DeleteBlogCtr) admin.POST("/save-blog-edit", ac.SaveBlogEditCtr) admin.GET("/editblog/:id", ac.EditBlogCtr) } // Listen and serve on 0.0.0.0:8080 r.Run(":8080") }