# HTTP Response Writer

Response Writer digunakan untuk mengeluarkan response saat suatu endpoint di hit.

## Contoh _code_ penggunaan response dengan pakcage http

```go
package main

import (
	"fmt"
	"net/http"
)

var Hello http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("Hello \n"))
	// fmt
	name := "member_01"
	fmt.Fprint(w, "Hello! \n", name)
	fmt.Fprintln(w, "Hello!", name)
	fmt.Fprintf(w, "Hello! %s", name)
}
	
func main() {
	server := http.Server{
		Addr:   "localhost:5000",
		Handler: Hello,
	}

	fmt.Printf("Server running on %s", server.Addr)
	err := server.ListenAndServe()
	if err != nil{
		panic(err.Error())
	}
}
```

<figure><img src="https://1578455751-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F09pucuEBc5BTaaur3uoo%2Fuploads%2FTv5a8I8fYD9Pu9TvlO3x%2FRes.png?alt=media&#x26;token=44280fbe-e8a3-4705-acf0-43ec4a24628d" alt=""><figcaption></figcaption></figure>

## Contoh response JSON dengan map

Ada kalanya response yang dibutuhkan dalam bentuk JSON. Berikut contoh _code_ untuk membuat response dalam bentuk JSON.

```go
package main

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

var Hello http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	res := map[string]interface{}{
		"Status": http.StatusOK,
		"Message": http.StatusText(http.StatusOK),
	}
	jsonByte, err := json.Marshal(res)
	if err != nil {
		panic(err)
	}
	w.Write([]byte(jsonByte))
}
	
func main() {
	server := http.Server{
		Addr:   "localhost:5000",
		Handler: Hello,
	}

	fmt.Printf("Server running on %s", server.Addr)
	err := server.ListenAndServe()
	if err != nil{
		panic(err.Error())
	}
}
```

![](https://1578455751-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F09pucuEBc5BTaaur3uoo%2Fuploads%2FDRY9QiOZqjHezMneHhI5%2Fimage.png?alt=media\&token=1c1cad3f-30d4-4ae2-9a71-c348ab3dcccd)

## Contoh response JSON dengan struct

```go
package main

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

type Res struct {
	Status int
	Message string
}
var Hello http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	res := Res{
		Status: http.StatusOK, 
		Message: http.StatusText(http.StatusOK),
	}

	jsonByte, err := json.Marshal(res)
	if err != nil {
		panic(err)
	}
	w.Write([]byte(jsonByte))
}
	
func main() {
	server := http.Server{
		Addr:   "localhost:5000",
		Handler: Hello,
	}

	fmt.Printf("Server running on %s", server.Addr)
	err := server.ListenAndServe()
	if err != nil{
		panic(err.Error())
	}
}
```

<figure><img src="https://1578455751-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F09pucuEBc5BTaaur3uoo%2Fuploads%2Fi5dV61c9Wxkp9wDSQbmD%2FStruct%20Map.png?alt=media&#x26;token=ca3f533e-260c-4c6d-9121-cddef5231d07" alt=""><figcaption></figcaption></figure>
