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())
	}
}

Last updated