Implemented as a simple REST API
- $ go run main.go
- $ curl http://localhost:8080/api/oddnumbers/1/10 Returns an array of odd numbers in the range
Implemented as a simple REST API
| package main | |
| //create an http server with router | |
| import ( | |
| "context" | |
| "encoding/json" | |
| "github.com/gorilla/mux" | |
| "log" | |
| "net/http" | |
| "strconv" | |
| "time" | |
| ) | |
| func main() { | |
| httpServer := &http.Server{ | |
| Addr: ":8080", | |
| Handler: initRouter(), | |
| ReadTimeout: 5 * time.Second, | |
| WriteTimeout: 5 * time.Second, | |
| } | |
| log.Println("HTTP server is listening ...") | |
| log.Fatal(httpServer.ListenAndServe()) | |
| } | |
| func initRouter() *mux.Router { | |
| router := mux.NewRouter() | |
| router.HandleFunc("/api/oddnumbers/{l}/{r}", oddNumbers).Methods("GET") | |
| return router | |
| } | |
| func oddNumbers(w http.ResponseWriter, req *http.Request) { | |
| ctx, cancel := context.WithCancel(context.Background()) | |
| defer cancel() | |
| vars := mux.Vars(req) | |
| l, err := strconv.Atoi(vars["l"]) | |
| r, err := strconv.Atoi(vars["r"]) | |
| errorHandler(err, ctx) | |
| results := findOddNumbersInRange(l, r) | |
| j, err := json.Marshal(&results) | |
| errorHandler(err, ctx) | |
| w.Header().Set("Content-Type", "application/json; charset=utf8") | |
| w.Write(j) | |
| } | |
| func findOddNumbersInRange(l, r int) []int { | |
| var results []int | |
| for i := l; i <= r; i++ { | |
| if i%2 != 0 { | |
| results = append(results, i) | |
| } | |
| } | |
| return results | |
| } | |
| func errorHandler(err error, ctx context.Context) { | |
| ctx, cancel := context.WithCancel(ctx) | |
| defer cancel() | |
| if err != nil { | |
| log.Fatalf("Error marshaling data %v\n", err.Error()) | |
| cancel() | |
| } | |
| } |