in Go

Web API Development with Go – #2

Web Development with Go – Practice #2

In this example application, we’ll write to the screen by getting the parameter coming from the URI. We’ll also use a URI pattern to ensure that this parameter is a numeric value, adding an important property.

To install gorilla/mux package:

go get

Source code of the application:

package main

import (


type API struct {
	Message string "json:message"

func Hello(w http.ResponseWriter, r *http.Request) {
	urlParams := mux.Vars(r)
	id := urlParams["id"]
	messageConcat := "User ID: " + id

	message := API{messageConcat}
	output, err := json.Marshal(message)

	if err != nil {
		fmt.Println("An error occurred!")
	fmt.Fprintf(w, string(output))

func main() {
	gorillaRoute := mux.NewRouter()
	gorillaRoute.HandleFunc("/api/user/{id:[0-9]+}", Hello)
	http.Handle("/", gorillaRoute)
	http.ListenAndServe(":8080", nil)


Good Luck
Cihan Özhan

Write a Comment