> For the complete documentation index, see [llms.txt](https://davidwinalda94.gitbook.io/mastering-golang/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://davidwinalda94.gitbook.io/mastering-golang/go-basic-for-web-development/web-service-api-server.md).

# Web Service API Server

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

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

![](https://2969676661-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MQaVepPFjuLoNjbs6f8%2F-MTBnx_WwuSmau2ludpD%2F-MTBsKtabUj8kxwvDNvD%2FScreen%20Shot%202021-02-10%20at%2023.58.24.png?alt=media\&token=7da9a773-c6af-477f-b7fc-b0744b332f5b)

![](https://2969676661-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MQaVepPFjuLoNjbs6f8%2F-MTBnx_WwuSmau2ludpD%2F-MTBsYN77GZ8UYqwNLgb%2FScreen%20Shot%202021-02-10%20at%2023.59.19.png?alt=media\&token=6c151614-eeb0-4b0b-ac1e-7e1b4633a445)
