create a rest endpoint using mux in go

To create a REST endpoint using mux in Go, you can follow the below steps:

  1. First, import the necessary packages:
main.go
import (
    "encoding/json"
    "github.com/gorilla/mux"
    "log"
    "net/http"
)
85 chars
7 lines
  1. Then, create a new mux router:
main.go
r := mux.NewRouter()
21 chars
2 lines
  1. Use the r.HandleFunc method to create the endpoint and define the HTTP method to handle:
main.go
r.HandleFunc("/users", getUsers).Methods(http.MethodGet)
57 chars
2 lines
  1. Define the function which would handle the request/response for the endpoint:
main.go
func getUsers(w http.ResponseWriter, r *http.Request) {
    // your code to fetch the users data and return the response
}
123 chars
4 lines
  1. Inside this function, you can define the logic to fetch users' data, format the response data, and write it to the response:
main.go
func getUsers(w http.ResponseWriter, r *http.Request) {
    // fetch user data from database or service
    users := []User{{ID: 1, Name: "John Doe"}, {ID: 2, Name: "Jane Doe"}}
    // create a response object and set the content type
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    // convert the response data to JSON and write to response
    if err := json.NewEncoder(w).Encode(users); err != nil {
        log.Fatalf("failed to encode response data: %v", err)
    }
}
517 chars
12 lines
  1. Finally, start the server using the http.ListenAndServe method and pass the router as an argument:
main.go
log.Fatal(http.ListenAndServe(":8080", r))
43 chars
2 lines

With the above steps, you have successfully created a REST endpoint using mux in Go!

related categories

gistlibby LogSnag