👨‍💻
Dokumentasi Golang (PT Phincon)
  • 🚀Dokumentasi Bootcamp (PT Phincon)
  • Command di Golang
  • Static Type di Golang
  • Variable and Constant
    • Variable daI Constant
    • Deklarasi Variabel
    • Iota (Auto Increment)
    • Blank Identifier (Variable Underscore)
    • Access Modifier (Public or Private)
  • Tipe Data Primitif
    • Integer dan Unsigned Integer
    • Float dan Complex
    • String
    • Boolean
  • Tipe Data Aggregate
    • Array
    • Struct
  • Tipe Data Reference
    • Slice
    • Map
    • Function in Golang
      • Function
      • Function vs Method
      • Function vs Procedure
      • Private vs Public Function
      • Function Init dan Main
      • Function dengan Return Multiple Value
      • Variadic Function
      • Function sebagai Parameter
      • Anonymous Function
      • Input Function dari CLI
      • Exercise (Function)
  • Default Value setiap Tipe Data
  • Type Declaration di Golang
    • Type Declaration
    • Type Declaration Built-In di Golang
  • Kebab Case, Camel Case, Snake Case & Pascal Case di Golang
  • Konversi Tipe Data
  • If-Else dan Switch
    • If Else
    • Switch
    • Exercise
  • Looping
    • Looping For
    • Looping for range
    • Infinite Looping
    • Penerapan Looping pada Sorting
  • Operator di Golang
    • Arithmetic Operator
    • Assignment Operator
    • Relational Operator
    • Logic Operator
  • Interface
  • Interface Kosong atau Any
  • Nil
  • Pointer
    • Pass By Value dan Pass By Reference
    • Pointer (Pass By Reference)
    • Operator Address (& dan *)
    • Default Value Pointer
    • Tricky Case
    • Pointer pada Parameter di Function
    • Pointer pada Method
  • Package
    • Fmt
    • Rand
    • Os
    • Strings
      • To Lower
      • Contains
      • Split
      • Trim
      • Atoi
      • Itoa
      • EqualFold
    • Random Generator
    • Time
      • Get Current Time By Location
      • Time Sleep
      • Time Since
      • Timer & After
      • AfterFunc
      • Ticker & Tick
  • Go dan JSON
    • JSON vs XML
    • Unmarshal vs Marshal
    • Marshal (Go Object -> JSON)
    • Unmarshal (JSON -> Go Object)
    • Streaming Decoder & Encoder
    • Tag
    • JSON Go Return Byte
  • Go dan CSV
    • Insert Data ke File CSV
    • Insert 1.000.000 Data ke File CSV
  • Goroutine
    • Concurrency vs Parrarel
    • Go Routine Sederhana
    • Go Routine vs Synchronous
    • Wait Group
    • Defer
    • Channel
    • Buffered Channel
    • Select Channel
    • Deadlock - All goroutines are asleep
    • Race Condition
    • Mutex (Mutual Exclusion)
    • RW Mutex vs Mutex
    • Once
    • Pool
    • Atomic
    • Go Max Procs
    • Exit
    • Exercise 1 : Go Routine + Context + Channel
    • Exercise 2 : Worker (Go Routine + Channel + Context)
    • Exercise 3 : Random Worker (Go Routine + Channel + Context)
    • Exercise : Implementasi Goroutine dan Channel pada File CSV
  • Go Context
    • Pengenalan Context
    • Context Background & TODO
    • Context With Value
    • Context WithDeadline dan Context WithTimeout
    • Context WithCancel dan Context Done
  • Pengenalan HTTP
  • Go Native HTTP
    • HTTP Server
    • HTTP Server Multi Handler
    • HTTP Server dengan Serve Mux
    • HTTP Response Writer
    • HTTP Test
    • Routing
    • Konsep Middleware
    • Middleware
    • Get Query Parameter
    • Get Path Parameter
    • Request JSON
    • Request Form
    • Get dan Set Header
    • Get dan Set Cookie
    • Redirect
    • Serve File
    • Upload File
    • Download File
    • Hit Endpoint dengan Curl di Terminal
  • Go Gin Framework
    • HTTP Server
    • Router
    • Middleware
    • Get Query Parameter
    • Get Path Parameter
    • Request JSON
    • Request Form
    • Get dan Set Header
    • Get dan Set Cookie
    • Redirect
    • Serve File
    • Upload File
    • Download File
  • Golang dan Database
    • Instalasi MySQL dengan Docker Desktop
    • Instalasi PostgreSQL dengan Docker
    • Basic SQL
    • SQL Join
    • SQL Relation
    • Golang Database Driver
    • Golang dan SQL
  • Go Unit Test
    • Method di Package Testing
    • Package Assert & Require
    • Running Sub Test
    • Table Test
    • Generate Coverage Unit Testing dalam Bentuk HTML
  • Sonar Qube dan Sonar Scanner
  • Logging
  • Golang dan Redis
  • Golang dan RabbitMQ
    • Instalasi RabbitMQ dengan Docker
    • Instalasi Package RabbitMQ di Golang
    • Publisher dan Consumer
    • Publisher dan Multi Consumer
    • Setting RabbitMQ (Durable, Auto Delete dan Ack)
  • Git Command
  • Git Clone dengan SSH
  • Anotasi dan Package di Java Spring Boot
Powered by GitBook
On this page
  • Contoh code middleware di beberapa router group
  • Contoh code middleware di beberapa route
  • Contoh code middleware sebelum dan sesudah suatu handler
  1. Go Gin Framework

Middleware

Untuk membuat middleware di Golang bisa menggunakan method Use seperti code di bawah ini. Setiap group route juga dapat dibuat middleware yang berbeda.

Contoh code middleware di beberapa router group

package main

import (
	"log"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.Use(Logging())
	// router group
	r1 := r.Group("/api1")
	r2 := r.Group("/api2")
	// middleware
	r1.Use(ErrorMiddleware())
	r2.Use(LoggingTime())

	r1.GET("/welcome", Welcome)
	r1.POST("/welcome", Welcome)
	r2.GET("/welcome", Welcome)
	r2.POST("/welcome", Welcome)

	r.Run(":5000")
}

func Welcome(ctx *gin.Context) {
	log.Println("Welcome")
}

func ErrorMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		if ctx.GetHeader("Content-Type") != "" {
			ctx.Redirect(http.StatusMovedPermanently, "https://www.bing.com/")
		} else {
			ctx.Redirect(http.StatusMovedPermanently, "http://www.google.com/")
		}
		defer func() {
			err := recover()
			if err != nil {
				log.Println(err.(error))
			}
		}()
	}
}

func Logging() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		status := ctx.Writer.Status()
		log.Println("middleware before", ctx.Request.Method, status)
		ctx.Next()
		log.Println("middleware after", ctx.Request.Method, status)
	}
}

func LoggingTime() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		start := time.Now()
		log.Println("start from", start)
		ctx.Next()
		log.Println("end at", time.Since(start).Seconds())
	}
}

Contoh code middleware di beberapa route

Middleware juga bisa di set untuk 1 route tertentu. Pada code di bawah ini middleware ErrorMiddleware() dan LoggingTime() di set sebelum handler Welcome.

package main

import (
	"log"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.Use(Logging())
	r1 := r.Group("/api1")
	r2 := r.Group("/api2")

	r1.GET("/welcome", ErrorMiddleware(), Welcome)
	r1.POST("/welcome", ErrorMiddleware(), Welcome)
	r2.GET("/welcome", LoggingTime(), Welcome)
	r2.POST("/welcome", LoggingTime(), Welcome)

	r.Run(":5000")
}

func Welcome(ctx *gin.Context) {
	log.Println("Welcome")
}

func ErrorMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		if ctx.GetHeader("Content-Type") != "" {
			ctx.Redirect(http.StatusMovedPermanently, "https://www.bing.com/")
		} else {
			ctx.Redirect(http.StatusMovedPermanently, "http://www.google.com/")
		}
		defer func() {
			err := recover()
			if err != nil {
				log.Println(err.(error))
			}
		}()
	}
}

func Logging() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		status := ctx.Writer.Status()
		log.Println("middleware before", ctx.Request.Method, status)
		ctx.Next()
		log.Println("middleware after", ctx.Request.Method, status)
	}
}

func LoggingTime() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		start := time.Now()
		log.Println("start from", start)
		ctx.Next()
		log.Println("end at", time.Since(start).Seconds())
	}
}

Contoh code middleware sebelum dan sesudah suatu handler

Di Gin juga memungkinkan untuk membuat middleware sebelum dan setelah suatu handler. Sebagai contoh handler welcome memiliki 2 middleware yang dijalankan sebelum dan sesudah handler tersebut dijalankan.

package main

import (
	"log"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()

	r.GET("/welcome", mid1, mid2, welcome, mid3, mid4)
	r.Run(":5000")
}

func mid1(ctx *gin.Context) {
	log.Println("mid1")
}

func mid2(ctx *gin.Context) {
	log.Println("mid2")
}

func welcome(ctx *gin.Context) {
	ctx.Writer.Write([]byte("success"))
	// ctx.Abort() -> menghentikan handler sampai disini
}

func mid3(ctx *gin.Context) {
	log.Println("mid3")
}

func mid4(ctx *gin.Context) {
	log.Println("mid4")
}
PreviousRouterNextGet Query Parameter

Last updated 1 year ago