Generally, we use the response.Write() method to send the response to the API call. In the below code, we are sending a response by converting a string to byte.
Here is the sample code.
package main
import (
"net/http"
"github.com/gorilla/mux"
)
func main() {
route := mux.NewRouter()
route.HandleFunc("/", func(response http.ResponseWriter, request *http.Request) {
response.WriteHeader(http.StatusOK)
response.Write([]byte("Hello World"))
})
http.ListenAndServe(":8000", route)
}
But there is a better way to send a response from the API. You can send Json response using json.Marshal, This method will give the Json string that can be sent to the Client.
Here is the sample code.
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/gorilla/mux"
)
type person struct {
Name string
LastName string
Age uint8
}
func sendResponse(response http.ResponseWriter, request *http.Request) {
person := person{Name: "Shashank", LastName: "Tiwari", Age: 30}
jsonResponse, jsonError := json.Marshal(person)
if jsonError != nil {
fmt.Println("Unable to encode JSON")
}
fmt.Println(string(jsonResponse))
response.Header().Set("Content-Type", "application/json")
response.WriteHeader(http.StatusOK)
response.Write(jsonResponse)
}
func main() {
route := mux.NewRouter()
route.HandleFunc("/", sendResponse)
http.ListenAndServe(":8000", route)
}In the above code, we converted the person structs to JSON string using json.Marshal.
Checkout more GoLang tutorials.





