Mastering Golang
  • Tentang Go
  • Instalasi Go
  • Membuat Project Go
  • Go Run & Go Build
  • Apa itu Package pada Go
  • Imports dan Exports
  • Variabel
  • Tipe Data
  • Konstanta dan Komentar
  • Operator
  • Type Conversion
  • Kondisional - IF
  • Kondisional - Switch Case
  • Looping
  • Array
  • Array - Looping
  • Slices
  • Pointer
  • Map
  • Fungsi
  • Struct
  • Method
  • Interface
  • Interface Kosong
  • Concurrency
  • Concurrency - Goroutines
  • Channel
  • Buffered Channel
  • Channel - Close and Range
  • Channel - Direction
  • Channel - Select
  • Concurrency - WaitGroup
  • Concurrency - Mutex
  • JSON Data
  • SQL
  • URL Parsing
  • GO Vendor
  • Unit Testing
  • Go Basic for Web Development
    • Aplikasi Web pada Go - Hello World
    • Root Routing
    • Query String
    • Web Service API Server
    • HTTP Basic Auth
    • RESTFul API dengan Gin dan Gorm
Powered by GitBook
On this page

Was this helpful?

  1. Go Basic for Web Development

Web Service API Server

Web Service API adalah sebuah aplikasi web yang menerima request dari client dan menghasilkan response, biasanya berupa JSON/XML.

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
)

type Student struct {
	ID       string
	Fullname string
	Age      int
	Batch    string
}

var data = []Student{
	{"001", "Wisma", 25, "Adorable"},
	{"002", "Yudis", 22, "Brilliant"},
	{"003", "Guntur", 30, "Creative"},
	{"004", "Sukisno", 35, "Dilligent"},
}

func handlerUsers(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	if r.Method == "POST" {
		result, err := json.Marshal(data)

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Write(result)
		return
	} else {
		http.Error(w, "", http.StatusBadRequest)
	}
}

func handlerUser(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	if r.Method == "POST" {
		id := r.FormValue("id")

		for _, student := range data {
			if student.ID == id {
				result, err := json.Marshal(student)

				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}

				w.Write(result)
				return
			}
			http.Error(w, "Student not found", http.StatusBadRequest)
			return
		}
	}

	http.Error(w, "", http.StatusBadRequest)
}

func main() {
	http.HandleFunc("/users", handlerUsers)
	http.HandleFunc("/user", handlerUser)

	port := "localhost:8080"

	log.Println("Server started at", port)

	err := http.ListenAndServe(port, nil)

	if err != nil {
		fmt.Println(err.Error())
	}
}
PreviousQuery StringNextHTTP Basic Auth

Last updated 4 years ago

Was this helpful?