func DownloadDtD(c *gin.Context) { c.Header("Content-Type", "text/xml; charset=\"utf-8\"") url := c.Request.URL.RequestURI()[1:] timeout := time.Duration(5 * time.Second) client := http.Client{ Timeout: timeout, } resp, err := client.Get(fmt.Sprintf("http://%s", url)) if resp.StatusCode != 200 { c.String(http.StatusServiceUnavailable, "fail to reach baclend") return } body, err := ioutil.ReadAll(resp.Body) if err != nil { c.String(http.StatusInternalServerError, "fail to read body") } defer resp.Body.Close() if len(body) == 0 { c.String(http.StatusServiceUnavailable, "fail to read body") return } c.Header("Cache-Control", "max-age=436800") c.String(http.StatusOK, string(body)) filePath := fmt.Sprintf("%s%s", *cachePath, c.Request.URL.Path) paths := strings.Split(filePath, "/") err = os.MkdirAll(strings.Join(paths[:len(paths)-1], "/"), os.ModeDir|os.ModePerm) err = ioutil.WriteFile(filePath, body, 0644) if err != nil { return } }
// PreAbort will set the appropriate HTTP Basic header. func (m HTTPBasicAuth) PreAbort(c *gin.Context, auth *AuthInfo, err *AuthErr) { if m.Realm == "" { m.Realm = "Authorization Required" } m.Realm = "Basic realm=" + strconv.Quote(m.Realm) c.Header("WWW-Authenticate", m.Realm) }
func badgeImageScwBuildEndpoint(c *gin.Context) { name := c.Param("name") images := cache.GetImageByName(name) left := "build" c.Header("Content-Type", "image/svg+xml;charset=utf-8") switch len(images) { case 0: c.String(http.StatusNotFound, devhub.ErrBadge(left, fmt.Errorf("no such image"))) case 1: image := images[0] if image.Objects.Api == nil { c.String(http.StatusInternalServerError, devhub.ErrBadge(left, fmt.Errorf("invalid resource"))) return } creationDate, err := time.Parse(time.RFC3339, image.Objects.Api.CreationDate) if err != nil { c.String(http.StatusInternalServerError, devhub.ErrBadge(left, fmt.Errorf("invalid-date"))) return } humanTime := humanize.Time(creationDate) humanTime = strings.Replace(humanTime, " ago", "", -1) badge, err := devhub.GetBadge(left, humanTime, "green") if err != nil { c.String(http.StatusInternalServerError, badge) return } c.String(http.StatusOK, badge) default: c.String(http.StatusNotFound, devhub.ErrBadge(left, fmt.Errorf("ambiguous name"))) } }
func view(c *gin.Context) { id := c.Param("uniuri") key := c.Param("key") re := models.ResourceEntry{} remote := c.ClientIP() db.Where(&models.ResourceEntry{Key: id}).First(&re) if re.Key == "" { log.Printf("[INFO][%s]\tNot found : %s", remote, id) c.AbortWithStatus(http.StatusNotFound) return } log.Printf("[INFO][%s]\tFetched %s file and entry\n", remote, id) f, err := os.Open(path.Join(conf.C.UploadDir, re.Key)) if err != nil { log.Printf("[ERROR][%s]\tWhile opening %s file\n", remote, id) c.AbortWithStatus(http.StatusInternalServerError) return } block, err := aes.NewCipher([]byte(key)) if err != nil { log.Printf("[ERROR][%s]\tDuring Cipher creation : %s\n", remote, err) c.String(http.StatusInternalServerError, "Something went wrong on the server side. Try again later.") c.AbortWithStatus(http.StatusInternalServerError) return } var iv [aes.BlockSize]byte stream := cipher.NewCFBDecrypter(block, iv[:]) reader := &cipher.StreamReader{S: stream, R: f} c.Header("Content-Disposition", "filename=\""+re.Name+"\"") io.Copy(c.Writer, reader) }
func Home(c *gin.Context) { input := Form{} if err := c.Bind(&input); err != nil { c.AbortWithError(http.StatusInternalServerError, err) return } if input.Attempt >= 3 { c.Redirect(http.StatusFound, "/goodbye") return } content := TwiML{ Gather: &Gather{ Action: fmt.Sprintf("/auth?Attempt=%d", input.Attempt), Method: "POST", Say: "Please enter your authorization code", }, Redirect: &Redirect{ Method: "GET", Action: fmt.Sprintf("/?Attempt=%d", input.Attempt+1), }, } c.Header("Content-Type", "text/xml") io.WriteString(c.Writer, `<?xml version="1.0" encoding="UTF-8" ?>`) xml.NewEncoder(c.Writer).Encode(content) }
func Generate8bit(c *gin.Context) { name := c.Param("name") gender := c.Param("gender") switch { case gender == "m": gender = "male" case gender == "f": gender = "female" case gender == "male" || gender == "female": //do nothing default: c.AbortWithError(http.StatusInternalServerError, errors.New("Invalid parameters")) return } log.Println(name) InitAssets() img := GenerateIdenticon8bits(gender, []byte(name)) c.Header("Content-Type", "image/png") c.Stream(func(w io.Writer) bool { png.Encode(w, img) return false }) }
// Discovery : templates the rkt discovery data func (wh *WebHandler) Discovery(c *gin.Context) { logger.Debug(c.Request.RequestURI) logger.Debug(c.Request.Host) queryMap := c.Request.URL.Query() _, ok := queryMap["ac-discovery"] logger.Info("%v", queryMap) if ok { t := rktTmpl{} t.BaseIP = wh.config.BaseIP t.HostName = c.Request.Host t.AciName = c.Params.ByName("name") logger.Notice("Rocket file : %s", t.AciName) // random etags for the win c.Header("ETag", time.Now().String()) err := tmpl.ExecuteTemplate(c.Writer, "rocket", t) if err != nil { logger.Error("template error ", err) } return } else { AciName := c.Params.ByName("name") fh, size, err := RocketACI.Get(AciName) if err != nil { logger.Error("Rocket file error : %s", err) c.AbortWithStatus(404) } logger.Notice("Serving ACI : %s", AciName) if size > 0 { c.Writer.Header().Set("Content-Length", strconv.FormatInt(size, 10)) } io.Copy(c.Writer, fh) } }
// View handles the file views func View(c *gin.Context) { var err error id := c.Param("uniuri") re := models.Resource{} if err = re.Get(id); err != nil || re.Key == "" { logger.InfoC(c, "server", "Not found", id) c.AbortWithStatus(http.StatusNotFound) return } re.LogFetched(c) f, err := os.Open(path.Join(conf.C.UploadDir, re.Key)) if err != nil { logger.ErrC(c, "server", fmt.Sprintf("Couldn't open %s", re.Key), err) c.AbortWithStatus(http.StatusInternalServerError) return } if conf.C.AlwaysDownload { c.Header("Content-Type", "application/octet-stream") } c.Header("Content-Disposition", "filename=\""+re.Name+"\"") io.Copy(c.Writer, f) if re.Once { re.Delete() re.LogDeleted(c) } }
func parse(c *gin.Context) { c.Header("Access-Control-Allow-Origin", "*") c.Header("Access-Control-Allow-Headers", "origin, content-type, accept") var json Request err := c.BindJSON(&json) if err != nil || json.Link == "" { c.JSON(http.StatusBadRequest, gin.H{"message": "Incrorrect request"}) return } link := json.Link u, err := url.Parse(link) if err != nil { c.JSON(400, gin.H{"message": "Broken link", "link": link}) return } id := insertUrl(u.String()) go grab(u, id) c.JSON(http.StatusCreated, gin.H{"message": "processing", "id": id, "link": link}) }
func (as ApiService) serviceCreate(c *gin.Context) { var newService types.Service if err := c.BindJSON(&newService); err != nil { c.Error(err) c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } //Guarantees that no one tries to create a destination together with a service newService.Destinations = []types.Destination{} if _, errs := govalidator.ValidateStruct(newService); errs != nil { c.Error(errs) c.JSON(http.StatusBadRequest, gin.H{"errors": govalidator.ErrorsByField(errs)}) return } // If everthing is ok send it to Raft err := as.balancer.AddService(&newService) if err != nil { c.Error(err) if err == types.ErrServiceAlreadyExists { c.JSON(http.StatusConflict, gin.H{"error": err.Error()}) } else { c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("UpsertService() failed: %v", err)}) } return } c.Header("Location", fmt.Sprintf("/services/%s", newService.Name)) c.JSON(http.StatusCreated, newService) }
func Dial(c *gin.Context) { c.Header("Content-Type", "text/xml") io.WriteString(c.Writer, `<?xml version="1.0" encoding="UTF-8" ?> <Response> <Dial timeout="10">510-529-9511</Dial> </Response>`) }
func IndexHtml(c *gin.Context) { html := createHtml("メニュー画面", []string{"/js/$c.js", "/js/$v.js", "/js/index.js", "/js/_cjsx.js", "/js/indexjsx.js"}, []string{"/js/lib/fluxxor.js", "/js/lib/react.js", "/js/lib/react-bootstrap.js", "/js/lib/jquery-1.11.1.js", "/js/lib/lodash.js"}, []string{"/css/bootstrap.css", "/css/main.css"}, []string{}) c.Header("Content-Type", "text/html") c.String(200, html) }
func (o *OptionsHandler) Tasks(c *gin.Context) { c.Header("Allow", "POST, PUT, DELETE") c.JSON(http.StatusCreated, TasksOptions{ "POST": Method{ Description: "Creates new task.", Parameters: taskParameters, Example: map[string]interface{}{ "Title": "Test task", "Description": "Test description", "Priority": 1, "CompletedAt": time.Now().Format(time.RFC3339), "IsDeleted": false, "IsCompleted": true, }, }, "PUT": Method{ Description: "Updates task fields by task ID", Parameters: Parameters{ Parameter{ "taskId": ParameterOption{ "type": "int", "description": "Task id to update.", "required": true, }, "task": taskParameters, }, }, Example: map[string]interface{}{ "taskId": 1, "task": map[string]interface{}{ "Title": "Test task", "Description": "Test description", "Priority": 1, "CompletedAt": time.Now().Format(time.RFC3339), "IsDeleted": false, "IsCompleted": true, }, }, }, "DELETE": Method{ Description: "Mar task as deleted by task ID", Parameters: Parameters{ Parameter{ "id": ParameterOption{ "type": "int", "description": "Task ID to delete", "required": true, }, }, }, Example: map[string]int{ "id": 1, }, }, }) }
func Buzz(c *gin.Context) { c.Header("Content-Type", "text/xml") io.WriteString(c.Writer, `<?xml version="1.0" encoding="UTF-8" ?> <Response> <Play>/static/DTMF-9.mp3</Play> <Play>/static/DTMF-pound.mp3</Play> </Response>`) }
func certHandler(c *gin.Context) { if strings.Contains(c.Request.UserAgent(), "Firefox") { c.Header("content-type", "application/x-x509-ca-cert") c.File("ca.cert.cer") return } noFirefoxTemplate.Execute(c.Writer, gin.H{ "url": "http://" + c.Request.Host + c.Request.URL.String(), }) }
func (s *DefaultServer) commandSpeedTest(c *gin.Context, args Args) { size := args.GetInt64(argTestSize) if size <= 0 || size > size100MB { size = size100MB } c.Header(headerContentLength, strconv.FormatInt(size, intBase)) _, err := io.CopyN(c.Writer, speedTest{}, size) if err != nil { log.Println("speed test error", err) } }
// GET http://localhost:8080/users/1 // func (u UserResource) findUser(c *gin.Context) { log.Println("Request from User: "******"user")) id := c.Param("user-id") usr := u.users[id] if len(usr.Id) == 0 { c.Header("Content-Type", "text/plain") c.AbortWithError(http.StatusNotFound, new(ErrorUserNotFound)) return } c.JSON(http.StatusOK, usr) }
func (auth *UserAuthenticator) BasicAuthForUser(c *gin.Context) bool { u, p, _ := c.Request.BasicAuth() if auth.AuthenticateUser(u, p) { return true } c.Header("WWW-Authenticate", "Basic realm=\"Status Dashboard\"") c.String(http.StatusUnauthorized, "Login required.") c.Abort() return false }
// Options is a middleware function that appends headers // for options requests and aborts then exits the middleware // chain and ends the request. func Options(c *gin.Context) { if c.Request.Method != "OPTIONS" { c.Next() } else { c.Header("Access-Control-Allow-Origin", "*") c.Header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS") c.Header("Access-Control-Allow-Headers", "authorization, origin, content-type, accept") c.Header("Allow", "HEAD,GET,POST,PUT,PATCH,DELETE,OPTIONS") c.Header("Content-Type", "application/json") c.AbortWithStatus(200) } }
func getJob(c *gin.Context) { c.Header("Access-Control-Allow-Origin", "*") c.Header("Access-Control-Allow-Headers", "origin, content-type, accept") id := c.Param("id") json, err := selectJob(id) if err != nil { c.JSON(http.StatusNotFound, gin.H{"message": "error", "error": err}) return } c.JSON(http.StatusOK, json) }
func GenerateGitHub(c *gin.Context, name string, width, margin int) { if width < 32 || width-margin < 10 { c.AbortWithError(http.StatusInternalServerError, errors.New("Invalid parameters")) return } img := GenerateIdenticon([]byte(name), width, margin) c.Header("Content-Type", "image/png") c.Stream(func(w io.Writer) bool { png.Encode(w, img) return false }) }
func (this GamesController) Create(ginContext *gin.Context) { game, err := models.Game{}.Create(this.Context.AeContext, this.Player()) game.Url = this.ResourceUrl(baseURL, game.Id) if err.Any() { this.RespondWith.UnexpectedError(err) return } ginContext.Header("location", game.Url) ginContext.JSON(http.StatusCreated, game) }
func (s *MockServer) fire(mock Mock, i int, c *gin.Context) { s.mutex.Lock() s.Mocks[i].Count = s.Mocks[i].Count + 1 s.mutex.Unlock() for header, val := range mock.HttpResponse.Headers { c.Header(header, val) } c.String( mock.HttpResponse.StatusCode, mock.HttpResponse.Body, ) }
func (mw *GinJWTMiddleware) unauthorized(c *gin.Context, code int, message string) { if mw.Realm == "" { mw.Realm = "gin jwt" } c.Header("WWW-Authenticate", "JWT realm="+mw.Realm) c.Abort() mw.Unauthorized(c, code, message) return }
func (ar *APIResource) Authenticate(c *gin.Context) { var u models.User err := json.NewDecoder(c.Request.Body).Decode(&u) if err != nil { log.Printf("Error decoding JSON: %s\n", err) } if u.Auth() { ar.Authenticated = true c.Header("Authorization", "authenticated") } else { c.Error(errors.New("Failed to authenticate")) c.String(http.StatusForbidden, "Failed to authenticate") } }
func (s *Server) handleAPINodes(c *gin.Context) { result := make(nodeResponseList, 0) for _, n := range s.config.Poller.Nodes { result = append(result, nodeResponse{ Name: n.Name, Label: n.Label, }) } sort.Sort(result) c.Header("Cache-Control", "private, max-age=0") c.JSON(http.StatusOK, result) }
func stop(c *gin.Context) { agentID := c.Param("agentID") a, _ := mdb.GetAgent(agentID) resp, _ := http.Post("http://"+a.IP+":"+a.Port+"/"+APIBASE+"/stop", "application/json", c.Request.Body) c.Header("Access-Control-Allow-Origin", "*") c.Header("Access-Control-Allow-Headers", "access-control-allow-origin, access-control-allow-headers") if resp.StatusCode != 200 { c.JSON(resp.StatusCode, resp.Body) return } c.JSON(resp.StatusCode, Message{"Container stopped."}) }
func (s *Server) handleAPIHosts(c *gin.Context) { hs := set.New(set.ThreadSafe) // Get hosts list hosts, _ := s.poller.GetHosts() for _, h := range hosts { hs.Add(h.Name) } // Get unique set of hosts names result := set.StringSlice(hs) sort.Strings(result) c.Header("Cache-Control", "private, max-age=0") c.JSON(http.StatusOK, result) }
func (s *Sensorserver) GetChart(c *gin.Context) { // Load Template // Can't use c.HTML(), because the html template function escape " t, _ := template.ParseFiles(s.conf.TemplateDir + "/chart.js") s.conf.Type = c.Param("type") durationInSeconds := s.duration(c.Query("duration")) f := make(map[string]interface{}) for _, sensor := range s.conf.Sensors { data, err := s.fetchLastData(sensor, durationInSeconds) if err != nil { log.Println(err.Error()) c.String(http.StatusInternalServerError, err.Error()) return } if s.conf.Type == "single" { f[sensor] = s.reduceData(data) } else { f[sensor] = s.getMinMaxPerDay(data) } } f["plotBands"] = s.GetSunriseAndSunset() f["type"] = s.conf.Type c.Header("Content-Type", "application/javascript; charset=utf-8") t.Execute(c.Writer, f) }
func (o *OptionsHandler) AuthJwt(c *gin.Context) { c.Header("Allow", "POST") c.JSON(http.StatusCreated, TasksOptions{ "POST": Method{ Description: "Check user credentials and return jwt token", Parameters: Parameters{ Parameter{ "username": ParameterOption{ "type": "string", "description": "Username", "required": true, }, "password": ParameterOption{ "type": "string", "description": "Password", "required": true, }, }, }, Example: map[string]interface{}{ "username": "******", "password": "******", }, }, }) }