本文整理汇总了Golang中github.com/valyala/fasthttp.RequestCtx.SetContentType方法的典型用法代码示例。如果您正苦于以下问题:Golang RequestCtx.SetContentType方法的具体用法?Golang RequestCtx.SetContentType怎么用?Golang RequestCtx.SetContentType使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/valyala/fasthttp.RequestCtx
的用法示例。
在下文中一共展示了RequestCtx.SetContentType方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ExpvarHandler
// ExpvarHandler dumps json representation of expvars to http response.
//
// Expvars may be filtered by regexp provided via 'r' query argument.
//
// See https://golang.org/pkg/expvar/ for details.
func ExpvarHandler(ctx *fasthttp.RequestCtx) {
expvarHandlerCalls.Add(1)
ctx.Response.Reset()
r, err := getExpvarRegexp(ctx)
if err != nil {
expvarRegexpErrors.Add(1)
fmt.Fprintf(ctx, "Error when obtaining expvar regexp: %s", err)
ctx.SetStatusCode(fasthttp.StatusBadRequest)
return
}
fmt.Fprintf(ctx, "{\n")
first := true
expvar.Do(func(kv expvar.KeyValue) {
if r.MatchString(kv.Key) {
if !first {
fmt.Fprintf(ctx, ",\n")
}
first = false
fmt.Fprintf(ctx, "\t%q: %s", kv.Key, kv.Value)
}
})
fmt.Fprintf(ctx, "\n}\n")
ctx.SetContentType("application/json; charset=utf-8")
}
示例2: idHandlerFunc
func idHandlerFunc(ctx *fasthttp.RequestCtx, idWorker *goflake.IdWorker, retry int) {
ua := string(ctx.UserAgent())
var (
id uint64
err error
)
for i := 0; i < retry; i++ {
id, err = idWorker.GetId(ua)
if err == nil {
break
}
}
r := map[string]string{
"id": strconv.FormatUint(id, 10),
}
if strings.HasSuffix(string(ctx.Path()), ".msgpack") {
ctx.SetContentType("application/x-msgpack; charset=UTF-8")
if err := codec.NewEncoder(ctx, mh).Encode(r); err != nil {
ctx.Error(err.Error(), fasthttp.StatusInternalServerError)
}
} else {
ctx.SetContentType("application/json; charset=UTF-8")
if err := json.NewEncoder(ctx).Encode(r); err != nil {
ctx.Error(fmt.Sprintf(`{"error":"%v"}`, err.Error()), fasthttp.StatusInternalServerError)
}
}
}
示例3: requestHandler
func requestHandler(ctx *fasthttp.RequestCtx) {
fmt.Fprintf(ctx, "Hello, world!\n\n")
fmt.Fprintf(ctx, "Request method is %q\n", ctx.Method())
fmt.Fprintf(ctx, "RequestURI is %q\n", ctx.RequestURI())
fmt.Fprintf(ctx, "Requested path is %q\n", ctx.Path())
fmt.Fprintf(ctx, "Host is %q\n", ctx.Host())
fmt.Fprintf(ctx, "Query string is %q\n", ctx.QueryArgs())
fmt.Fprintf(ctx, "User-Agent is %q\n", ctx.UserAgent())
fmt.Fprintf(ctx, "Connection has been established at %s\n", ctx.ConnTime())
fmt.Fprintf(ctx, "Request has been started at %s\n", ctx.Time())
fmt.Fprintf(ctx, "Serial request number for the current connection is %d\n", ctx.ConnRequestNum())
fmt.Fprintf(ctx, "Your ip is %q\n\n", ctx.RemoteIP())
fmt.Fprintf(ctx, "Raw request is:\n---CUT---\n%s\n---CUT---", &ctx.Request)
ctx.SetContentType("text/plain; charset=utf8")
// Set arbitrary headers
ctx.Response.Header.Set("X-My-Header", "my-header-value")
// Set cookies
var c fasthttp.Cookie
c.SetKey("cookie-name")
c.SetValue("cookie-value")
ctx.Response.Header.SetCookie(&c)
}
示例4: pubRawHandler
// /raw/msgs/:topic/:ver
func (this *Gateway) pubRawHandler(ctx *fasthttp.RequestCtx, params fasthttprouter.Params) {
var (
topic string
ver string
appid string
pubkey string
)
ver = params.ByName(UrlParamVersion)
topic = params.ByName(UrlParamTopic)
header := ctx.Request.Header
appid = string(header.Peek(HttpHeaderAppid))
pubkey = string(header.Peek(HttpHeaderPubkey))
if err := manager.Default.OwnTopic(appid, pubkey, topic); err != nil {
log.Error("app[%s] %s %+v: %v", appid, ctx.RemoteAddr(), params, err)
ctx.SetConnectionClose()
ctx.Error("invalid secret", fasthttp.StatusUnauthorized)
return
}
cluster, found := manager.Default.LookupCluster(appid)
if !found {
log.Error("cluster not found for app: %s", appid)
ctx.Error("invalid appid", fasthttp.StatusBadRequest)
return
}
var out = map[string]string{
"store": "kafka",
"broker.list": strings.Join(meta.Default.BrokerList(cluster), ","),
"topic": manager.Default.KafkaTopic(appid, topic, ver),
}
b, _ := json.Marshal(out)
ctx.SetContentType("application/json; charset=utf8")
ctx.Write(b)
}
示例5: Handler
func (a *API) Handler(ctx *fasthttp.RequestCtx) {
ctx.SetContentType("application/json")
ctx.Response.Header.Set("Access-Control-Allow-Origin", "*")
switch string(ctx.Path()) {
case "/rules":
j, err := json.Marshal(a.Proxy.Rules)
if err != nil {
ctx.Error(fmt.Sprintf("{\"error\": \"%v\"}", err), 500)
return
}
ctx.Write(j)
case "/rules/reload":
if err := a.Proxy.ReloadRules(a.RuleFile); err != nil {
ctx.Error(fmt.Sprintf("{\"error\": \"%v\"}", err), 500)
return
}
log.Println("Rule file reloaded")
ctx.Write([]byte("{\"status\": \"ok\"}"))
default:
ctx.Error("{\"error\": \"Not found\"}", fasthttp.StatusNotFound)
}
}
示例6: fortuneHandler
func fortuneHandler(ctx *fasthttp.RequestCtx) {
rows, err := db.Query("fortuneSelectStmt")
if err != nil {
log.Fatalf("Error selecting db data: %v", err)
}
fortunes := make([]templates.Fortune, 0, 16)
for rows.Next() {
var f templates.Fortune
if err := rows.Scan(&f.ID, &f.Message); err != nil {
log.Fatalf("Error scanning fortune row: %s", err)
}
fortunes = append(fortunes, f)
}
rows.Close()
fortunes = append(fortunes, templates.Fortune{Message: "Additional fortune added at request time."})
sort.Sort(common.FortunesByMessage(fortunes))
ctx.SetContentType("text/html; charset=utf-8")
templates.WriteFortunePage(ctx, fortunes)
}
示例7: ServeHTTP
// ServeHTTP is called whenever there is a new request.
// This is quite similar to JavaEE Servlet interface.
func (h *MyHandler) ServeHTTP(ctx *fasthttp.RequestCtx) {
// In the future we can use requester can detect request spammers!
// requester := ctx.RemoteAddr()
// Increase request count
count := &(h.requests)
atomic.AddUint64(count, 1)
if ctx.IsGet() {
url := ctx.URI()
operations, format, err, invalid := ParseURI(url, h.imageSource, h.watermarker)
if err != nil {
ctx.NotFound()
logging.Debug(err)
return
}
if invalid != nil {
ctx.Error(invalid.Error(), 400)
return
}
blob, err := h.operator.GetBlob(operations...)
if err != nil {
ctx.NotFound()
logging.Debug(err)
} else {
ctx.SetContentType("image/" + format)
ctx.Write(blob)
logging.Debug("Blob returned")
}
} else if ctx.IsPost() {
// POST is currently unused so we can use this for testing
h.RetrieveHello(ctx)
logging.Debug("Post request received")
}
}
示例8: ResJSON
// ResJSON 响应Json数据
func (fs *FastServer) ResJSON(ctx *fasthttp.RequestCtx, ti oauth2.TokenInfo) (err error) {
data := map[string]interface{}{
"access_token": ti.GetAccess(),
"token_type": fs.cfg.TokenType,
"expires_in": ti.GetAccessExpiresIn() / time.Second,
}
if scope := ti.GetScope(); scope != "" {
data["scope"] = scope
}
if refresh := ti.GetRefresh(); refresh != "" {
data["refresh_token"] = refresh
}
buf, err := json.Marshal(data)
if err != nil {
return
}
ctx.Response.Header.Set("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate")
ctx.Response.Header.Set("Pragma", "no-cache")
ctx.Response.Header.Set("Expires", "Fri, 01 Jan 1990 00:00:00 GMT")
ctx.SetContentType("application/json;charset=UTF-8")
ctx.SetStatusCode(200)
_, err = ctx.Write(buf)
return nil
}
示例9: fortuneHandler
// Test 4: Fortunes
func fortuneHandler(ctx *fasthttp.RequestCtx) {
rows, err := fortuneSelectStmt.Query()
if err != nil {
log.Fatalf("Error selecting db data: %v", err)
}
fortunes := make([]Fortune, 0, 16)
for rows.Next() {
var f Fortune
if err := rows.Scan(&f.Id, &f.Message); err != nil {
log.Fatalf("Error scanning fortune row: %s", err)
}
fortunes = append(fortunes, f)
}
rows.Close()
fortunes = append(fortunes, Fortune{Message: "Additional fortune added at request time."})
sort.Sort(FortunesByMessage(fortunes))
ctx.SetContentType("text/html")
if err := tmpl.Execute(ctx, fortunes); err != nil {
log.Fatalf("Error executing fortune: %s", err)
}
}
示例10: jsonMarshal
func jsonMarshal(ctx *fasthttp.RequestCtx, v interface{}) {
ctx.SetContentType("application/json")
if err := json.NewEncoder(ctx).Encode(v); err != nil {
log.Fatalf("error in json.Encoder.Encode: %s", err)
}
}
示例11: PlaintextHandler
func PlaintextHandler(ctx *fasthttp.RequestCtx) {
ctx.SetContentType("text/plain")
ctx.WriteString("Hello, World!")
}
示例12: hello
func hello(ctx *fasthttp.RequestCtx) {
ctx.SetContentType("text/plain; charset=utf8")
ctx.Write([]byte("hello world"))
}