A Simple Go (golang) API Template

In order to make starting a new Go project easy for myself, I decided to write a minimalist go API as a template. I recently started learning the Go programming language (golang). When I think about things I’d like to write with Go, most of them are web based.

So, here’s my basic API template in Go.

package main

import (
	"fmt"
	"io"
	"net/http"
)

const port = "8086"

func main() {
	fileServer := http.FileServer(http.Dir("./www"))
	http.Handle("/", fileServer)
	http.HandleFunc("/search", searchHandler)
	fmt.Printf("Server started on port %s\n", port)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		fmt.Printf(err.Error())
	}
}

func searchHandler(w http.ResponseWriter, r *http.Request) {
	query := r.URL.Query().Get("q")
	io.WriteString(w, "Searched for "+query+"\n")
}

Here’s a more complex version that doesn’t have a default file server but has some examples of more complex content types.

package main

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

const port = "8086"

func main() {
	// Set some port variables
	const port = "8086"
	const address = ":" + port
	// Setup functions to handle various URI's
	http.HandleFunc("/", rootHandler)
	http.HandleFunc("/text", textHandler)
	http.HandleFunc("/json", jsonHandler)
	// Start a server
	fmt.Printf("Server started on port %s\n", port)
	if err := http.ListenAndServe(address, nil); err != nil {
		log.Fatal(err)
	}
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("content-type", "text/html")
	io.WriteString(w, "Welcome. Try the <em>/text</em> or <em>/json</em> endpoint.\n")
}

func textHandler(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "Text\n")
	io.WriteString(w, "URL.Path = "+r.URL.Path)
}

func jsonHandler(w http.ResponseWriter, r *http.Request) {
	// Setup a response structure
	type Response struct {
		Result  bool
		Message string
	}
	// Create a data variable that holds response values
	data := Response{
		Result:  true,
		Message: "You are awesome",
	}
	// Convert the data structure to json data
	jsonData, err := json.Marshal(data)
	if err != nil {
		fmt.Printf("That's an error, yo.")
		log.Println(err)
	}
	// Output the json data
	w.Header().Add("content-type", "application/json")
	io.WriteString(w, string(jsonData))
}


Joel's Newsletter

Get a monthly digest of what I'm up to.

Subscribe by Email