TicTacGo - An Intro to Golang
Introduction
I am a true beginner to the Go Programming Language and to solidify some of the basics I have acquired I set out on creating a naughts and crosses (tic-tac-toe) server as an introductory project. You can find the project on my Github here.
Board
Board is the struct I created to contain the current board state, the grid but more accurately the state contains the 9 cells in the grid and their contents.
At a given point, I cell on the grid can either contain nothing, “O” or “X”, where the latter two represent a naught and a cross respectively.
The struct contains only one attribute: Squares, of type [9]string.
However, the Board struct has several related methods:
DrawBoard() string:: returns a string which contains the HTML representation of the board.Reset():: resets the board to an empty state.CheckLegal(i int) bool:: checks if a given move is legal in the current state (i.e. if the move correlates to an actual cell in the grid and that cell is empty).CheckWin(x string) bool:: where x should be “O” or “X”, checks to see if the given player is in a winning state.
The API
The net/http package (see docs here) provides a very convenient way of creating an API.
Creating the endpoints is as simple as writing a handler function for the endpoint and then assigning that function to an endpoint.
Then serve the API using the http.ListenAndServe function.
See below for a bare-bones but complete example of a net/http API.
// Example net/http API
package main
import (
"fmt"
"log"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Here is a response!")
}
func main(){
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
In TicTacGo, I use the API to register moves made by players.
Specifically I have use a handler on the root endpoint / called makeMove.
makeMove retrieves the player’s move from the path using r.URL.Path where r is passed to the handler function as an *http.Request.
This is an impractical way to accept URL arguments and is far from standard but it is also not a concern for the tiny scope of this project.
makeMove follows the following steps:
- Accesses player’s move from path.
- Checks the move is legal (if it isn’t no move is made and the input is ignored).
- Makes the move by updating the
Squaresattribute of theBoardstruct with the appropriate character (“O” or “X”). - Checks for a win condition; if there a player has won than it sends a message to say so before resetting the
BoardwithReset(); else it waits for the next move.
By using the URL as a way for the player to make moves it allows me to embed buttons within the HTML representation of the board. This means that when the player clicks on the top-right cell on the board, the server will register their move with that cell.
I hope you enjoyed reading this blog post! Sign up to my newsletter here: