home‎ > ‎go‎ > ‎

HTTP UUID Service

Please refer to the UUID generator,  you need to build and install it. To install it you need to have it under GOPATH. Please refer to go documentation or type "go help" on the command console.

Here is the code for HTTP UUID Server.

package main

import (
    "fmt"
    "log"
    "net/http"
    "strconv"
    "uuid"
)

// uuid, the web server
func UUIDServer(w http.ResponseWriter, req *http.Request) {
    values := req.URL.Query()
    count := 1
    var err error
    if values != nil {
        cnt := values.Get("count")
        if cnt != "" {
            count, err = strconv.Atoi(cnt)
            if err != nil {
                fmt.Fprintf(w, "{\"Error\":\"%s\"}\n", err)
                return
            } 
        }
    }
    for ; count > 0; count -= 1 {
        uuid, err := uuid.GenUUID()
        if err != nil {
            fmt.Fprintf(w, "{\"Error\":\"%s\"}\n", err)
        } else {
            fmt.Fprintf(w, "{\"uuid\":[\"%s\"]}\n", uuid)
        }
    }
}

func main() {
    http.HandleFunc("/_uuid", UUIDServer)
    err := http.ListenAndServe(":12345", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

Compile and run it.

 go run uid_srv.go

This will spawn a server at localhost port 12345
To test it, run the command

curl -X GET "http://127.0.0.1:12345/_uuid?count=2"

Output:
{"uuid":["dccc3a2340ff48e28045576961d2dad2"]}
{"uuid":["0fcad33e405695ea8046acb5fd0fd758"]}

You can vary the count parameter to change the output UUID count.

 Source code is attached below.

ċ
uid_srv.go
(1k)
Ashish Banerjee,
May 16, 2012, 10:09 AM
Comments