about summary refs log tree commit diff
path: root/main.go
blob: ae81e964c5ec2397c22d0917760cb486d2824fda (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main

import (
	"encoding/json"
	"fmt"
	"github.com/gorilla/mux"
	"log"
	"math"
	"net/http"
	"strconv"
)

// Defining the constants used in the NFWHandler profile
const (
	sigma float64 = 200
	f0    float64 = 0.1
	G     float64 = 4.302e-3
	rS    float64 = 1e4
)

type result struct {
	NFW float64 `json:"NFWHandler"`
}

// The actual NFWHandler profile
// Uses the given distance to the middle of the galaxy to calculate the probability that a star is generated
func rho(x float64, y float64, z float64) float64 {
	r := math.Sqrt(math.Pow(x, 2) + math.Pow(y, 2) + math.Pow(z, 2))
	a := (1) / (math.Sqrt(2*math.Pi) * sigma)
	b := math.Exp(-phi(r) / math.Pow(sigma, 2))
	return a * b
}

// A subset of the NFWHandler function in order to handle the 0 case
func phi(x float64) float64 {
	if x == 0 {
		return -4 * math.Pi * f0 * G * math.Pow(rS, 2)
	}
	a := -(4 * math.Pi * f0 * G * math.Pow(rS, 3)) / x
	b := math.Log(1.0 + (x / rS))
	return a * b
}

// NFWHandler is the corresponding HTTP-handler to the NFWHandler Profile
// It uses the given distance to the Midpoint of the galaxy to calculate and return the probability that a star
// is generated.
func NFWHandler(w http.ResponseWriter, r *http.Request) {
	params := r.URL.Query()

	// parse the parameters
	x, _ := strconv.ParseFloat(params.Get("x"), 64)
	y, _ := strconv.ParseFloat(params.Get("y"), 64)
	z, _ := strconv.ParseFloat(params.Get("z"), 64)

	// calculate the NFWHandler-value
	var returnValue result = result{rho(x, y, z)}
	log.Print(returnValue)
	b, err := json.Marshal(returnValue)
	if err != nil {
		panic(err)
	}

	// http response writer
	w.Header().Set("Content-Type", "application/json")
	_, err = fmt.Fprintf(w, "%v", string(b))
	if err != nil {
		panic(err)
	}
}

// IndexHandler handles request on the / endpoint
func IndexHandler(w http.ResponseWriter, r *http.Request) {
	log.Print(fmt.Fprintln(w, "usage: nfw.docker.localhost/NFWHandler?x=<x>&y=<y>&z=<z>"))
}

func main() {
	router := mux.NewRouter()

	// routes
	router.HandleFunc("/", IndexHandler).Methods("GET")

	router.HandleFunc("/NFWHandler", NFWHandler).Methods("GET")

	log.Println("Starting the service on port localhost:8081")
	log.Fatal(http.ListenAndServe(":8081", router))
}