HTTP Response

Introduction

You can use ctx.Response() for HTTP response in the Controller.

String

import "github.com/goravel/framework/contracts/http"

ctx.Response().String(http.StatusOK, "Hello Goravel")

JSON

import (
  "github.com/goravel/framework/contracts/http"
)

ctx.Response().Json(http.StatusOK, http.Json{
  "Hello": "Goravel",
})

ctx.Response().Json(http.StatusOK, struct {
  ID       uint `json:"id"`
  Name     string `json:"name"`
}{
  Id:      1,
  Front:   "Goravel",
})

Custom Return

ctx.Response().Data(http.StatusOK, "text/html; charset=utf-8", []byte("<b>Goravel</b>"))

Response File

import "net/http"

ctx.Response().File("./public/logo.png")

Download File

import "net/http"

ctx.Response().Download("./public/logo.png", "1.png")

Attach Header

import "github.com/goravel/framework/contracts/http"

ctx.Response().Header("Content", "Goravel").String(http.StatusOK, "Hello Goravel")

Use the Cookie method on the response instance to set a cookie. The Cookie method accepts a http.Cookie instance, which allows you to set various cookie options.

import (
  "time"
  "github.com/goravel/framework/contracts/http"
)

ctx.Response().Cookie(http.Cookie{
  Name: "name",
  Value: "Goravel",
  Path: "/",
  Domain: "goravel.dev",
  Expires: time.Now().Add(24 * time.Hour),
  Secure: true,
  HttpOnly: true,
})

Use the WithoutCookie method to remove a cookie.

ctx.Response().WithoutCookie("name")

Return Success

ctx.Response().Success().String("Hello Goravel")
ctx.Response().Success().Json(http.Json({
  "Hello": "Goravel",
}))

Custom Code

ctx.Response().Status(http.StatusOK).Json(http.Json{
  "hello": "Goravel",
})

Redirect

ctx.Response().Redirect(http.StatusMovedPermanently, "https://goravel.dev")

No Content

ctx.Response().NoContent()
ctx.Response().NoContent(http.StatusOk)

Get Response

You can obtain all the information from ctx.Response(), which is commonly used in HTTP middleware:

origin := ctx.Response().Origin()

origin contains some methods as shown below:

MethodAction
BodyGet response data
HeaderGet response header
SizeGet response size
StatusGet response status