These steps cover writing and running your application:
- From your Terminal or console application, create a new directory called ~/projects/go-programming-cookbook/chapter14/fastweb and navigate to this directory.
- Run this command:
$ go mod init github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter14/fastweb
You should see a file called go.mod that contains the following:
module github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter14/fastweb
- Copy tests from ~/projects/go-programming-cookbook-original/chapter14/fastweb, or use this as an exercise to write some of your own code!
- Create a file called items.go with the following content:
package main
import (
"sync"
)
var items []string
var mu *sync.RWMutex
func init() {
mu = &sync.RWMutex{}
}
// AddItem adds an item to our list
// in a thread-safe way
func AddItem(item string) {
mu.Lock()
items = append(items, item)
mu.Unlock()
}
// ReadItems returns our list of items
// in a thread-safe way
func ReadItems() []string {
mu.RLock()
defer mu.RUnlock()
return items
}
- Create a file called handlers.go with the following content:
package main
import (
"encoding/json"
"github.com/valyala/fasthttp"
)
// GetItems will return our items object
func GetItems(ctx *fasthttp.RequestCtx) {
enc := json.NewEncoder(ctx)
items := ReadItems()
enc.Encode(&items)
ctx.SetStatusCode(fasthttp.StatusOK)
}
// AddItems modifies our array
func AddItems(ctx *fasthttp.RequestCtx) {
item, ok := ctx.UserValue("item").(string)
if !ok {
ctx.SetStatusCode(fasthttp.StatusBadRequest)
return
}
AddItem(item)
ctx.SetStatusCode(fasthttp.StatusOK)
}
- Create a file called main.go with the following content:
package main
import (
"fmt"
"log"
"github.com/buaazp/fasthttprouter"
"github.com/valyala/fasthttp"
)
func main() {
router := fasthttprouter.New()
router.GET("/item", GetItems)
router.POST("/item/:item", AddItems)
fmt.Println("server starting on localhost:8080")
log.Fatal(fasthttp.ListenAndServe("localhost:8080",
router.Handler))
}
- Run the go build command.
- Run the ./fastweb command:
$ ./fastweb
server starting on localhost:8080
- From a separate Terminal, test it our with some curl commands:
$ curl "http://localhost:8080/item/hi" -X POST
$ curl "http://localhost:8080/item/how" -X POST
$ curl "http://localhost:8080/item/are" -X POST
$ curl "http://localhost:8080/item/you" -X POST
$ curl "http://localhost:8080/item" -X GET
["hi","how", "are", "you"]
- The go.mod file may be updated and the go.sum file should now be present in the top-level recipe directory.
- If you have copied or written your own tests, run go test. Ensure that all the tests pass.