Skip to content

Commit

Permalink
Add basic go-micro web server with echo endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
nkprince007 committed May 23, 2018
1 parent 65d4066 commit ba09a6e
Show file tree
Hide file tree
Showing 5 changed files with 128 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
FROM alpine:3.2
ADD listen /listen
WORKDIR /
ENTRYPOINT [ "/listen" ]
14 changes: 14 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@

GOPATH:=$(shell go env GOPATH)

.PHONY: proto test docker


build:
go build -o listen

test:
go test -v ./... -cover

docker:
docker build . -t listen-web:latest
53 changes: 53 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Listen Service

This is the Listen service

Generated with

```
micro new gitlab.com/nkprince007/listen --namespace=go.micro --type=web
```

## Getting Started

- [Configuration](#configuration)
- [Dependencies](#dependencies)
- [Usage](#usage)

## Configuration

- FQDN: go.micro.web.listen
- Type: web
- Alias: listen

## Dependencies

Micro services depend on service discovery. The default is consul.

```
# install consul
brew install consul
# run consul
consul agent -dev
```

## Usage

A Makefile is included for convenience

Build the binary

```
make build
```

Run the service
```
./listen-web
```

Build a docker image
```
make docker
```
29 changes: 29 additions & 0 deletions handler/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package handler

import (
"encoding/json"
"net/http"
"time"
)

// Echo receives whatever was sent and posts it back
func Echo(w http.ResponseWriter, r *http.Request) {
// decode the incoming request as json
var request map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
http.Error(w, err.Error(), 500)
return
}

response := map[string]interface{}{
"payload": request,
"processedAt": time.Now().Format(time.RFC1123),
"status": "received",
}

// encode and write the response as json
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, err.Error(), 500)
return
}
}
28 changes: 28 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package main

import (
"github.com/micro/go-log"
"github.com/micro/go-web"
"gitlab.com/nkprince007/listen/handler"
)

func main() {
// create new web service
service := web.NewService(
web.Name("go.micro.web.listen"),
web.Version("latest"),
)

// register call handler
service.HandleFunc("/", handler.Echo)

// initialise service
if err := service.Init(); err != nil {
log.Fatal(err)
}

// run service
if err := service.Run(); err != nil {
log.Fatal(err)
}
}

0 comments on commit ba09a6e

Please sign in to comment.