本文整理匯總了Golang中github.com/gin-gonic/gin.Context.Header方法的典型用法代碼示例。如果您正苦於以下問題:Golang Context.Header方法的具體用法?Golang Context.Header怎麽用?Golang Context.Header使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/gin-gonic/gin.Context
的用法示例。
在下文中一共展示了Context.Header方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: DownloadDtD
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
}
}
示例2: PreAbort
// 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)
}
示例3: view
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)
}
示例4: badgeImageScwBuildEndpoint
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")))
}
}
示例5: View
// 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)
}
}
示例6: Generate8bit
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
})
}
示例7: Home
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)
}
示例8: Discovery
// 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)
}
}
示例9: parse
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})
}
示例10: GetChart
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)
}
示例11: AuthJwt
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": "Bender",
"password": "molly",
},
},
})
}
示例12: serviceCreate
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)
}
示例13: Dial
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>`)
}
示例14: IndexHtml
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)
}
示例15: Buzz
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>`)
}