7 Instalasi Library graphql-go dan Dependensi Tambahan
7 Instalasi Library graphql-go dan Dependensi Tambahan
Oleh: [Nama Anda], Engineer Backend
GraphQL telah menjadi salah satu standar baru dalam mendesain API modern. Salah satu library yang cukup populer untuk mengimplementasikan GraphQL di Go (Golang) adalah graphql-go
. Jika Anda baru memulai, artikel ini akan memandu Anda langkah demi langkah menginstalasi library graphql-go beserta dependensi tambahan yang sering digunakan dalam proyek nyata. Saya akan lengkapi juga dengan contoh kode, simulasi, serta diagram alur untuk memperjelas proses integrasi.
1. Persiapkan Lingkungan Go
Pastikan Anda sudah menginstal Go. Minimal versi 1.16. Periksa dengan:
1go versionBila belum ada, instalasi bisa dilakukan dari https://golang.org/dl/ .
2. Inisialisasi Project Baru
Kita akan memakai Go modules untuk mengelola dependensi. Buat folder projek baru dan inisialisasi modules:
1mkdir graphql-tutorial
2cd graphql-tutorial
3go mod init github.com/yourusername/graphql-tutorial3. Instalasi Library Utama: graphql-go
graphql-go adalah engine utama GraphQL di Go. Install dengan perintah:
1go get github.com/graph-gophers/graphql-go
2go get github.com/graph-gophers/graphql-go/relayIni akan menambahkan library graphql-go di go.mod.
Penjelasan Singkat Komponen:
| Library | Fungsi Utama |
|---|---|
github.com/graph-gophers/graphql-go | Parser dan executor query schema GraphQL |
github.com/graph-gophers/graphql-go/relay | Handler HTTP untuk endpoint GraphQL |
4. Pendukung Routing: chi
Sebenarnya, Anda bisa memakai http.ServeMux. Namun, dalam aplikasi nyata, package router seperti chi
sering digunakan.
1go get github.com/go-chi/chi/v5Contoh Integrasi Routing:
1import (
2 "net/http"
3 "github.com/go-chi/chi/v5"
4)
5
6func main() {
7 r := chi.NewRouter()
8 r.Post("/query", relayHandler) // relayHandler nanti kita definisikan
9 http.ListenAndServe(":8080", r)
10}5. Dependensi JSON: graphql-go-tools / Encoding
Library graphql-go tidak melakukan encoding/decoding JSON response secara otomatis. Kita akan memakai encoding bawaan Go (encoding/json), namun library pendamping sering digunakan juga, misal graphql-go-tools
.
1go get github.com/wundergraph/graphql-go-toolsTapi untuk permulaan, cukup encoding/json.
6. Dependency Injection & Middleware
Supaya kode tetap modular dan testable, direkomendasikan menggunakan dependency injection, misal google/wire , dan middleware seperti alice .
1go get github.com/justinas/alice
2go get github.com/google/wire7. Logging: zerolog
Logging sangat esensial. Salah satu library logging modern adalah zerolog
.
1go get github.com/rs/zerolog/logSimulasi: Setup Endpoint GraphQL Sederhana
Struktur Sederhana Project:
graph TD
A[main.go] --> B[chi router]
B --> C[GraphQL Schema]
C --> D[Resolver]
D -->|handle| E[relay.Handler]
Contoh Skema dan Resolver:
File: schema.graphql
1type Query {
2 hello: String!
3}File: main.go
1package main
2
3import (
4 "context"
5 "embed"
6 "net/http"
7 "github.com/go-chi/chi/v5"
8 "github.com/graph-gophers/graphql-go"
9 "github.com/graph-gophers/graphql-go/relay"
10 "github.com/rs/zerolog/log"
11)
12
13//go:embed schema.graphql
14var sdl embed.FS
15
16type resolver struct{}
17
18func (r *resolver) Hello() string {
19 log.Info().Msg("handling hello query")
20 return "Hello, graphql-go!"
21}
22
23func main() {
24 schemaStr, _ := sdl.ReadFile("schema.graphql")
25 schema := graphql.MustParseSchema(string(schemaStr), &resolver{})
26
27 r := chi.NewRouter()
28 // Middleware logging
29 r.Use(func(next http.Handler) http.Handler {
30 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
31 log.Info().Msgf("Request: %s %s", req.Method, req.URL.Path)
32 next.ServeHTTP(w, req)
33 })
34 })
35
36 r.Post("/query", (&relay.Handler{Schema: schema}).ServeHTTP)
37 log.Info().Msg("GraphQL server started at :8080")
38 http.ListenAndServe(":8080", r)
39}Coba Query via cURL:
1curl -X POST -d '{"query": "{ hello }"}' -H "Content-Type: application/json" localhost:8080/queryOutput:
1{"data":{"hello":"Hello, graphql-go!"}}Ringkasan Tabel Dependensi
| No | Library | Keterangan | Contoh Penggunaan |
|---|---|---|---|
| 1 | graphql-go | Engine GraphQL utama | Desain schema & proses query |
| 2 | graphql-go/relay | HTTP Handler GraphQL | Endpoint /query |
| 3 | go-chi/chi | Router ringan & modular | Routing endpoint |
| 4 | encoding/json | En/decoding JSON | Parsel response |
| 5 | zerolog | Logging modern & ringan | Log query/request/error |
| 6 | justinas/alice | Middleware chaining | Auth/logging wrapper |
| 7 | google/wire | Dependency injection | Modularisasi resolver |
Diagram Alur End-to-End
sequenceDiagram
participant C as Client
participant S as Web Server
participant G as GraphQL Handler
C->>S: POST /query { query }
S->>G: Parse and Validate Query
G->>G: Execute Resolver Function
G->>S: GraphQL Response JSON
S->>C: Response (data/error)
Penutup
Menginstal dan men-setup library GraphQL di Go membutuhkan pemahaman komponen-karena arsitekturnya sangat modular. Dengan kombinasi graphql-go, chi, dan zerolog yang tepat, Anda dapat menjalankan server GraphQL production-grade, sekaligus mudah dipelihara dan di-scale. Selanjutnya, pengembangan bisa ditingkatkan dengan integrasi authentication, batching, dan custom directive.
Jangan ragu melakukan eksperimen dengan dependensi lain sesuai kebutuhan projek Anda. Semoga artikel ini menjadi pijakan Anda membangun GraphQL API Go yang andal.
Referensi
- https://github.com/graph-gophers/graphql-go
- https://github.com/go-chi/chi
- https://github.com/rs/zerolog
- https://github.com/google/wire
- https://github.com/justinas/alice
Happy Coding! 🚀