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")

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")

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