👨‍💻
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 handler dengan http handle
  • Contoh code dengan HTTP handle func.
  1. Go Native HTTP

HTTP Server Multi Handler

Handler merupakan program yang berguna untuk menerima request dari client dan memberikan response ke client. Dalam package http mux terdapat 2 jenis handler yaitu http.Handle() dan http.HandleFunc(). HTTP handle menerima input handler dengan tipe Handler. Sementara HTTP handleFunc menerima input handler dengan tipe HandlerFunc.

Handler merupakan interface. Artinya semua variabel yang punya method ServeHTTP dapat dikatakan sama dengan Handler.

HandlerFunc merupakan variabel dengan tipe data func(ResponseWriter. *Request). Artinya semua fungsi yang memiliki input ResponseWriter dan *Request dapat dikatan sama dengan HandlerFunc. HandlerFunc dalam package http memiliki method ServeHTTP. Artinya HandlerFunc juga mirip seperti Handler.

Perbedaannya, suatu variabel dengan tipe Handle harus didefinisikan dengan method ServeHTTP, sementara variabel dengan tipe HandlerFunc tidak harus.

type Handler interface {
	ServeHTTP(ResponseWriter, *Request)
}
type HandlerFunc func(ResponseWriter, *Request)

// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
	f(w, r)
}

Contoh handler dengan http handle

Jika kita menggunakan http.Handle() maka harus membuat variabel yang punya method ServeHTTP terlebih dahulu seperti contoh code di bawah ini.

package main

import (
    "fmt"
    "net/http"
)

type HelloHandler struct{}

func (h *HelloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello!")
}

type WorldHandler struct{}

func (h *WorldHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "World!")
}

func main() {
    hello := HelloHandler{}
    world := WorldHandler{}

    http.Handle("/hello", &hello)
    http.Handle("/world", &world)

    err := http.ListenAndServe(":8080", nil)
	if err != nil {
		panic(err)
	}
}

Contoh code dengan HTTP handle func.

Jika kita menggunakan http.HandleFunc() tidak perlu membuat method ServeHTTP untuk handler karena sudah ada dalam package http.

package main

import (
    "fmt"
    "net/http"
)

func Hello(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodGet {
		name := r.URL.Query().Get("name")
		fmt.Fprintf(w, "Hello! : %s", name)
	} else if r.Method == http.MethodPost {
		name := r.URL.Query().Get("name")
		fmt.Fprintf(w, "Post Hello! : %s", name)
	}
}

func World(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "World!")
}

func main() {
    var hello http.HandlerFunc = Hello
    var world http.HandlerFunc = World

    http.HandleFunc("/hello", hello)
    http.HandleFunc("/world", world)

    err := http.ListenAndServe(":5000", nil)
    if err != nil {
        panic(err)
    }
}

Referensi:

PreviousHTTP ServerNextHTTP Server dengan Serve Mux

Last updated 1 year ago

LogoDifference between http.Handle and http.HandleFunc?Stack Overflow